1.发送HTTP POST请求的例子
使用说明:需要使用httpclient-4.5.2.jar(4.3版本及以下的不适用于本例)和httpcore-4.4.4.jar。详解见注释内容。
package httpclient;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
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 HttpClientDemo {
/**
* @Title: sendPost
* @Description: TODO 发送一个Post请求
* @Attention: HttpClients.createDefault()获取的httpclient对象缺乏自定义
* 一些方法不能用,比如设置CookieStore,比如设置代理的用户名密码等,这些都需要自定义而default情况下没有
* @param
* @return void
* @throws
* @author lzh
* @date 2017年7月6日 上午6:39:09
*/
public static void sendPost(){
//1.建立HttpClient默认对象
CloseableHttpClient httpclient = HttpClients.createDefault();
//1.1另外一种方法,HttpClientBuider可以统一设置请求属性,而不再针对某个htppclient设置属性
//HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//CloseableHttpClient httpclient1 = httpClientBuilder.build();
//1.2另外一种方法,HttpClients-->HttpClientBuilder-->自定义-->生成HttpClient
/*有用户名密码的代理设置*/
//创建认证,并设置认证范围
//CredentialsProvider credsProvider = new BasicCredentialsProvider();
//credsProvider.setCredentials(new AuthScope("172.16.0.5", 80),//可以访问的范围
// new UsernamePasswordCredentials("MyUserName", "MyPassWord"));//用户名和密码
//CloseableHttpClient httpclient2 = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
//2.创建post请求
HttpPost postRequest = new HttpPost("http://localhost:8080/ZT/aaa.demo");
//2.1设置请求属性(代理,连接时间,响应时间等等)
//HttpHost proxy = new HttpHost("172.16.0.5",80,"http");
/*这种设置方法是httpclient4.5版本的,4.3的设置方法不同*/
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)//连接超时
.setConnectionRequestTimeout(1000) //响应超时
.setSocketTimeout(5000)
//.setProxy(proxy)//设置代理
.build();
postRequest.setConfig(requestConfig);
//2.2设置请求头
//2.2.1设置协议版本"HTTP/1.1",非常严格,HTTP必须大写
ProtocolVersion pv = new ProtocolVersion("HTTP",1,1);
postRequest.setProtocolVersion(pv);
//2.2.2添加消息头
postRequest.addHeader(HttpHeaders.ACCEPT, "text/html");
postRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
postRequest.addHeader(HttpHeaders.USER_AGENT, "httpclient/4.5.2(java(1.7.0_71))");
//2.2.3添加cookie(由于是默认直接获得的httpclient只能手动添加)
postRequest.addHeader("Cookie","aaa=111;bbb=222");
//2.2.4处理session(session是放在cookie里的)!!!如何设置cookie的过期时间!!!???
postRequest.addHeader("Cookie", "aaa=111;JSESSIONID=E3E2I0Y7R3R3R334EANM6394");
//3.创建参数列表
List params = new ArrayList();
params.add(new BasicNameValuePair("parma","111"));
//4.创建UrlEntity,方便设置编码
UrlEncodedFormEntity uefEntity = null;
try {
uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
postRequest.setEntity(uefEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//------------------打桩打桩-----------------------------
System.out.println("请求行:"+postRequest.getRequestLine());
Header [] header = postRequest.getAllHeaders();
StringBuilder sb = new StringBuilder();
for(int i=0;i
2.发送HTTP上传文件请求
使用说明:需要使用httpclient-4.5.2.jar(4.3版本及以下的不适用于本例)和httpcore-4.4.4.jar以及httpmime-4.5.2。详解见注释内容。
package httpclient;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
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.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* @Title: PostFileUpload
* @Description: 文件上传的例子
* @author lzh
* @date 2017年7月6日 下午6:34:48
*/
public class PostFileUpload {
public static String postUrl = "http://localhost:8080/springMVCfileUpload/filesUpload.j";
public static String postUrl2 = "http://localhost:8080/ZT/aaa.demo";
/**
* @Title: sendPost
* @Description: TODO 发送一个Post请求进行文件上传
* @Attention: HttpClients.createDefault()获取的httpclient对象缺乏自定义
* 一些方法不能用,比如设置CookieStore,比如设置代理的用户名密码等,这些都需要自定义而default情况下没有
* @param
* @return void
* @throws
* @author lzh
* @date 2017年7月6日 上午6:39:09
*/
public static void sendPost(){
//1.建立HttpClient默认对象
CloseableHttpClient httpclient = HttpClients.createDefault();
//1.1另外一种方法,HttpClientBuider可以统一设置请求属性,而不再针对某个htppclient设置属性
//HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//CloseableHttpClient httpclient1 = httpClientBuilder.build();
//1.2另外一种方法,HttpClients-->HttpClientBuilder-->自定义-->生成HttpClient
/*有用户名密码的代理设置*/
//创建认证,并设置认证范围
//CredentialsProvider credsProvider = new BasicCredentialsProvider();
//credsProvider.setCredentials(new AuthScope("172.16.0.5", 80),//可以访问的范围
// new UsernamePasswordCredentials("MyUserName", "MyPassWord"));//用户名和密码
//CloseableHttpClient httpclient2 = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
//2.创建post请求
HttpPost postRequest = new HttpPost(postUrl2);
//2.1设置请求属性(代理,连接时间,响应时间等等)
//HttpHost proxy = new HttpHost("172.16.0.5",80,"http");
/*这种设置方法是httpclient4.5版本的,4.3的设置方法不同*/
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)//连接超时
.setConnectionRequestTimeout(1000) //响应超时
.setSocketTimeout(5000)
//.setProxy(proxy)//设置代理
.build();
postRequest.setConfig(requestConfig);
//2.2设置请求头
//2.2.1设置协议版本"HTTP/1.1",非常严格,HTTP必须大写
ProtocolVersion pv = new ProtocolVersion("HTTP",1,0);
postRequest.setProtocolVersion(pv);
//2.2.2添加消息头
postRequest.addHeader(HttpHeaders.ACCEPT, "text/html");
//postRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
postRequest.addHeader(HttpHeaders.USER_AGENT, "httpclient/4.5.2(java(1.7.0_71))");
//2.2.3添加cookie(由于是默认方式获得的httpclient只能手动添加,不能用CookieStore自动添加)
postRequest.addHeader("Cookie","aaa=111;bbb=222");
//2.2.4处理session(session是放在cookie里的)!!!如何设置cookie的过期时间!!!???
postRequest.addHeader("Cookie", "aaa=111;JSESSIONID=E3E2I0Y7R3R3R334EANM6394");
//3.创建参数列表
List params = new ArrayList();
params.add(new BasicNameValuePair("parma","111"));
//4.创建文件上传Entity,方便设置编码
//UrlEncodedFormEntity uefEntity = null;
//4.1创建builder对象
MultipartEntityBuilder meb = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//决定content-type消息头中charset的值
meb.setCharset(Charset.forName("utf-8"));
//决定content-type消息头中boundary的值(这个值用来分隔不同文件与字段,一般浏览器是随机生成的)
meb.setBoundary(UUID.randomUUID().toString().replaceAll("-", "")+"haha");
//表单普通字段
meb.addPart("param1",new StringBody("外流1",ContentType.create("text/plain", "UTF-8")));
meb.addPart("param2",new StringBody("第二个",ContentType.create("text/plain", "UTF-8")));
//表单文件字段
File file1 = new File("E://要哭.gif");
File file2 = new File("F://LOLCfg.ini");
//服务端用utf-8解析报文,不会中文乱码(一般服务端都要加Spring的那个编码过滤器)
meb.addPart("files", new FileBody(file1,ContentType.MULTIPART_FORM_DATA,"要哭.gif"));
//new FileBody(file, contentType, filename)
meb.addPart("files", new FileBody(file2));
HttpEntity he = meb.build();
//uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
postRequest.setEntity(he);
//------------------打桩打桩-----------------------------
System.out.println("请求行:"+postRequest.getRequestLine());
Header [] header = postRequest.getAllHeaders();
StringBuilder sb = new StringBuilder();
for(int i=0;i