1. apache HttpClient
用于替换jdk的httpclient,
官网文档 http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/fundamentals.htm
2.基本套路
1 2 3 4 5 6 7 8
| CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet("http://localhost/"); CloseableHttpResponse response = httpclient.execute(httpget); try { <...> } finally { response.close(); }
|
2.1 http请求
一个http请求对象,有HttpGet,HttpPost等,HttpGet接收一个uri作参数,可以用字符串比如 “http://localhost", 注意加上http://, 也可以用URIBuilder来生成,如下:
1 2 3 4 5 6 7 8 9 10 11
| URI uri = new URIBuilder() .setScheme("http") .setHost("www.google.com") .setPath("/search") .setParameter("q", "httpclient") .setParameter("btnG", "Google Search") .setParameter("aq", "f") .setParameter("oq", "") .build(); HttpGet httpget = new HttpGet(uri); System.out.println(httpget.getURI());
|
如果想设置内容,可以用 httpPost.setEntity()方法,最简单的是用StringEntity声明一个,
1 2 3
| String j1 = "xx" StringEntity entity1 = new StringEntity(j1); httpPost.setEntity(entity1);
|
也有setHeader这类实用的方法,
1
| httpPost.setHeader("Content-Type","application/json-rpc");
|
2.2 http response回复
response一般是httpclient执行execute() HttpPost返回的对象。
可以用response.getStatusLine().toString()得到返回码。
2.3 http entity实体
一般用EntityUtils的toString(myEntity)将实体转换为字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet("http://localhost/"); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len != -1 && len < 2048) { System.out.println(EntityUtils.toString(entity)); } else { // Stream content out } } } finally { response.close(); }
|
还能用低级的instream流来处理实体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet("http://localhost/"); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { // do something useful } finally { instream.close(); } } } finally { response.close(); }
|
2.4 basic认证套路
1 2 3 4 5 6 7
| CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin","PASSWORD"); credentialsProvider.setCredentials(AuthScope.ANY, credentials); CloseableHttpClient client = HttpClientBuilder.create() .setDefaultCredentialsProvider(credentialsProvider) .build();
|
创建CredentialsProvider对象,UsernamePasswordCredentials对象,然后用setCredentials方法将credentialsProvider设置。
之后使用HttpClientBuilder方法来构建一个添加过认证的client,之后的调用没有任何区别。