HttpClient使用学习
HttpClient Tutorial:http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/index.html
HttpClient是Apache HttpComponents中的一部分,下载地址:http://hc.apache.org/
转载:https://www.cnblogs.com/yangchongxing/p/9191073.html
目录:
===========================================================================
===========================================================================
1、简单的Get请求
package core; import java.io.InputStream;
import java.nio.charset.Charset; import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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 Test { public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
int code = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == code) {
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
try {
Charset charset = Charset.forName("UTF-8");
int len = 0;
byte[] buf = new byte[2048];
while( (len = inputStream.read(buf)) != -1 ) {
System.out.print(new String(buf, 0, len, charset));
}
} finally {
inputStream.close();
}
}
} finally {
response.close();
}
}
} }
2、文件上传
package com.yuanxingyuan.common.util; import java.io.File;
import java.io.IOException; import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; /**
* http client工具类
* @author 杨崇兴
*
*/
public class HttpClientUtil { public static String postFile(String url, File file) {
String result = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addBinaryBody("file", file);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(multipartEntityBuilder.build());
try {
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
EntityUtils.consume(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpClient);
}
return result;
} public static void main(String[] args) {
String result = HttpClientUtil.postFile("http://localhost:8080/upload/image",new File("E:/wx/image.jpg"));
System.out.println(result);
}
}
服务端使用servlet3.0
import java.io.IOException;
import java.util.Collection; import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part; import org.apache.catalina.core.ApplicationPart; /**
* Servlet implementation class Upload
*/
@WebServlet("/image")
@MultipartConfig
public class Upload extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public Upload() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Collection<Part> parts = request.getParts();
if (parts != null) {
for(Part part : parts){
ApplicationPart ap= (ApplicationPart) part;
String name = ap.getSubmittedFileName();
part.write("E:/"+name);
System.out.println("upload ok. " + name);
}
}
} }
package httpclient; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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; public class Main {
public static void main(String[] args) throws ClientProtocolException, IOException {
//https://www.baidu.com/s?wd=%E8%A5%BF%E5%AE%89
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name","西安"));
HttpPost post = new HttpPost("http://www.baidu.com/s?wd=西安");
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params);
post.setEntity(urlEncodedFormEntity);
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
InputStream inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while( (line = reader.readLine()) != null ) {
System.out.println(line);
}
reader.close();
response.close();
client.close();
}
}
3、请求配置
HttpGet httpGet = new HttpGet("http://localhost/demo/api/test/3");
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(10000)
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.build();
httpGet.setConfig(config);
4、拦截器
CloseableHttpClient httpClient = HttpClients.custom()
.addInterceptorLast(new HttpRequestInterceptor(){
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
String count = (String) context.getAttribute("count");
request.addHeader("count", count);
}
}).build();
HttpGet httpGet = new HttpGet("http://localhost/demo/test/3");
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(10000)
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.build();
httpGet.setConfig(config); HttpClientContext context = HttpClientContext.create();
context.setAttribute("count", "111"); CloseableHttpResponse httpResponse = httpClient.execute(httpGet, context);
int code = httpResponse.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == code) {
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
Charset charset = Charset.forName("UTF-8");
System.out.println(EntityUtils.toString(entity, charset));
}
}
httpResponse.close();
httpClient.close();
HttpClientBuilder addInterceptorFirst(final HttpResponseInterceptor itcp)
HttpClientBuilder addInterceptorFirst(final HttpRequestInterceptor itcp)
HttpClientBuilder addInterceptorLast(final HttpResponseInterceptor itcp)
HttpClientBuilder addInterceptorLast(final HttpRequestInterceptor itcp)
添加四种类型的拦截器
5、从链接管理获得链接
HttpClientContext context = HttpClientContext.create();
HttpClientConnectionManager manager = new BasicHttpClientConnectionManager();
HttpRoute route = new HttpRoute(new HttpHost("119.23.107.129", 80));
ConnectionRequest request = manager.requestConnection(route, null);
HttpClientConnection conn = request.get(10, TimeUnit.SECONDS);
if (conn.isOpen()) {
manager.connect(conn, route, 1000, context);
manager.routeComplete(conn, route, context);
manager.releaseConnection(conn, null, 1, TimeUnit.MINUTES);
}
6、链接管理池
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// Increase max total connection to 200
cm.setMaxTotal(200);
// Increase default max connection per route to 20
cm.setDefaultMaxPerRoute(20);
// Increase max connections for localhost:80 to 50
HttpHost localhost = new HttpHost("locahost", 80);
cm.setMaxPerRoute(new HttpRoute(localhost), 50);
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build();
7、连接保持活着策略
ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch(NumberFormatException ignore) {
}
}
}
HttpHost target = (HttpHost) context.getAttribute(
HttpClientContext.HTTP_TARGET_HOST);
if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) {
// Keep alive for 5 seconds only
return 5 * 1000;
} else {
// otherwise keep alive for 30 seconds
return 30 * 1000;
}
}};
CloseableHttpClient httpClient = HttpClients.custom().setKeepAliveStrategy(myStrategy).build();
8、SSL使用实例PKCS12证书
url 请求地址
xmlObj 发送xml数据
certKey 证书密钥
certPath 证书文件地址PKCS12证书
@SuppressWarnings("unchecked")
public static Map<String, String> httpsPostRequestCert(String url, String xmlObj, String certKey, String certPath) {
Map<String, String> wxmap = new HashMap<String, String>();
try {
// 指定读取证书格式为PKCS12
KeyStore keyStore = KeyStore.getInstance("PKCS12");
// 读取本机存放的PKCS12证书文件
FileInputStream instream = new FileInputStream(new File(certPath));
// 指定PKCS12的密码(商户ID)
keyStore.load(instream, certKey.toCharArray());
instream.close(); SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, certKey.toCharArray()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] {"TLSv1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); HttpPost httpPost = new HttpPost(url);
// 得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
httpPost.addHeader("Content-Type", "text/xml");
httpPost.setEntity(new StringEntity(xmlObj, "UTF-8"));
// 根据默认超时限制初始化requestConfig
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(30000).build();
// 设置请求器的配置
httpPost.setConfig(requestConfig); HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
//转换为Map
InputStream inputStream = entity.getContent();
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
Element root = document.getRootElement();
List<Element> elementList = root.elements();
for (Element e : elementList) {
wxmap.put(e.getName(), e.getText());
}
} catch (Exception e) {
wxmap.put("return_msg", e.getMessage());
}
return wxmap;
}