1.什么是HttpClient?
Http协议非常的重要,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性
它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),
即提高了开发的效率,也方便提高代码的健壮性。
因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。
2.HTTP协议的特点:(面试)
HTTP协议的主要特点可概括如下:
1.支持客户/服务器模式。
2.简单快速:客户向服务器请求服务时,只需传送请求方法和路径。请求方法常用的有GET、HEAD、POST。每种方法规定了客户与服务器联系的类型不同。
由于HTTP协议简单,使得HTTP服务器的程序规模小,因而通信速度很快。
3.灵活:HTTP允许传输任意类型的数据对象。正在传输的类型由Content-Type加以标记。
4.无连接:无连接的含义是限制每次连接只处理一个请求。服务器处理完客户的请求,并收到客户的应答后,即断开连接。采用这种方式可以节省传输时间。
5.无状态:HTTP协议是无状态协议。无状态是指协议对于事务处理没有记忆能力。缺少状态意味着如果后续处理需要前面的信息,则它必须重传,这样可能导致每次连接传送的数据量增大。另一方面,在服务器不需要先前信息时它的应答就较快。
3.使用方法
首先需要导入HttpClientjar包,具体可以到官网下载,下载地址: http://hc.apache.org/downloads.cgi
commons-codec-1.7.jar,commons-logging-1.1.1.jar,httpclient-4.2.2.jar,httpcore-4.2.2.jar
1. 创建HttpClient对象,最新版的httpClient使用实现类的是closeableHTTPClient,以前的default作废了。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接
4.HTTP实体的使用
因为一个实体既可以代表二进制内容又可以代表字符内容,它也支持字符编码(支持后者也就是字符内容)。
实体是当使用封闭内容执行请求,或当请求已经成功执行,或当响应体结果发功到客户端时创建的。
要从实体中读取内容,可以通过HttpEntity#getContent()方法从输入流中获取,
这会返回一个java.io.InputStream对象,或者提供一个输出流到HttpEntity#writeTo(OutputStream)方法中,这会一次返回所有写入到给定流中的内容。
当实体通过一个收到的报文获取时,HttpEntity#getContentType()方法和HttpEntity#getContentLength()方法可以用来读取通用的元数据,
如Content-Type和Content-Length头部信息(如果它们是可用的)。
因为头部信息Content-Type可以包含对文本MIME类型的字符编码,比如text/plain或text/html,HttpEntity#getContentEncoding()方法用来读取这个信息。如果头部信息不可用,那么就返回长度-1,而对于内容类型返回NULL。如果头部信息Content-Type是可用的,那么就会返回一个Header对象。
当为一个传出报文创建实体时,这个元数据不得不通过实体创建器来提供。
创建一个服务器程序:
package httpclient;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
String password = req.getParameter("password");
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().print("you login:name :"+name+"password:"+password);
}
}
5.GET请求
package httpclienttest;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class App {
public static void main(String[] args) throws ClientProtocolException, IOException {
// 设置请求参数的内容
String name = "liubo";
String password= "12345";
// 1.创建HttpClient的实例
CloseableHttpClient httpclient = HttpClients.createDefault();
String url = "http://localhost:8080/httpclient/getName.do?name="+ name + "&password=" + password;
// 2.创建HttpGet对象
HttpGet httpget = new HttpGet(url);
System.out.println("URI: "+httpget.getURI());
// 3.执行GET请求
CloseableHttpResponse response = httpclient.execute(httpget);
// 4.获取响应的内容
// 4.1 获取响应的实体内容
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 4.2 获取响应的状态
System.out.println(response.getStatusLine());
// 4.3 获取响应内容的长度
System.out.println("Response content length: " + entity.getContentLength());
// 4.4 获取响应的内容
System.out.println(EntityUtils.toString(entity));
// 5.关闭资源
httpclient.close();
response.close();
}
}
6.POST
package httpclienttest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class APP2 {
public static void main(String[] args) throws ClientProtocolException, IOException{
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost请求
HttpPost httppost = new HttpPost("http://localhost:8080/httpclient/getName.do");
// 创建参数队列
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("name", "刘波"));
list.add(new BasicNameValuePair("password","123456"));
// 创建请求实体
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list,"utf-8");
httppost.setEntity(uefEntity);
// 获得响应内容
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// 打印出实体内容
System.out.println(EntityUtils.toString(entity, "UTF-8"));
// 关闭资源
httpclient.close();
response.close();
}
}
7.文件的下载(如图片的请求)
package httpclienttest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class IMGAPP {
public static void main(String[] args) throws ClientProtocolException, IOException {
// 1.创建HttpClient的实例
CloseableHttpClient httpclient = HttpClients.createDefault();
String url = "http://localhost:8080/car/1.jpg";
// 2.创建HttpGet对象
HttpGet httpget = new HttpGet(url);
System.out.println("URI: "+httpget.getURI());
// 3.执行GET请求
CloseableHttpResponse response = httpclient.execute(httpget);
// 4.获取响应的内容
// 4.1 获取响应的实体内容
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 4.2 获取响应的状态
System.out.println(response.getStatusLine());
// 4.3 获取响应内容的长度
System.out.println("Response content length: " + entity.getContentLength());
// 4.4 响应的字节流 转存到本地
InputStream is = entity.getContent();
File file = new File("C:\\Users\\Administrator\\Desktop\\test\\1.jpg");
FileOutputStream fos = new FileOutputStream(file);
int content = is.read();
while(content!=-1){
fos.write(content);
content = is.read();
}
fos.close();
is.close();
// 5.关闭资源
httpclient.close();
response.close();
}
}
8.文件的上传(如:图片的上传)
服务器的编写
package httpclient;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class TestServlet1 extends HttpServlet {
/*
*
*/
private String message = "";
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
FileItemFactory fif = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fif);
upload.setHeaderEncoding("utf-8");
List<FileItem> items = null;
try {
items = upload.parseRequest(req);
} catch (FileUploadException e) {
e.printStackTrace();
}
if(items!=null){
for(FileItem item : items){
String fieldName = item.getFieldName();// 获得 字段名 (即表单中的 name属性的值)
if(item.isFormField()){// 普通表单项
System.out.println(item.getString());
}else{// 文件表单项目
if(fieldName.equals("photo")){
System.out.println("文件的名称 "+item.getName());
long size = item.getSize();// 表单内容大小
if(size>200*1024){
message = "文件过大";
}else{
String filedName = item.getName();// 获得文件名(包括类型名)
String typeName = filedName.substring(filedName.lastIndexOf(".")+1);
if(typeName.equals("png")||typeName.equals("jpg")||typeName.equals("gif")){
String pathName = this.getServletContext().getRealPath("/photo");
System.out.println(pathName);
// 解决同名文件覆盖
String uuidStr = UUID.randomUUID().toString().replace("-", "");
String uuidFileName = uuidStr+"."+typeName;
File dir = new File(pathName);
if(!dir.exists()){
dir.mkdir();
}
File file = new File(dir,uuidFileName);
try {
item.write(file);
message="上传成功";
} catch (Exception e) {
message = "上传失败";
e.printStackTrace();
}
}else{
message="文件类型不符合";
}
}
}
}
}
}
resp.getWriter().println("message: "+message);
}
}
HttpClient的编写
package httpclienttest;
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class upload {
public static void main(String[] args) throws ClientProtocolException, IOException {
// 1.创建HttpClient对象
CloseableHttpClient client = HttpClients.createDefault();
// 2.构建POST请求
HttpPost httpPost = new HttpPost("http://localhost:8080/httpclient/upload.do");
// 3.要上传的文件
File file = new File("C:\\Users\\Administrator\\Desktop\\test\\1.jpg");
// 4.构建文件体
FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA, "1.jpg");
// 5.构建普通表单项
StringBody stringBody = new StringBody("12", ContentType.MULTIPART_FORM_DATA);
// 6.创建Multipart实体
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// 7.设置参数和实体
builder.addPart("photo", fileBody);
builder.addPart("id", stringBody);
// 8.创建成HttpEntity实体对象
HttpEntity httpEntity = builder.build();
httpPost.setEntity(httpEntity);
// 9.发送请求,并获得响应
HttpResponse response = client.execute(httpPost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
System.out.println(EntityUtils.toString(respEntity));
}
}
}