支持自动转向虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 提供的主要的功能包括:
实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
支持 HTTPS 协议
支持代理服务器
官网 http://hc.apache.org/httpclient-3.x/
Httpclient4.2终于提供了Fluent API,使得api的写法极大简化
Request.Get("http://somehost/")
.connectTimeout(1000)
.socketTimeout(1000)
.execute().returnContent().asString();
Request.Post("http://somehost/do-stuff")
.useExpectContinue()
.version(HttpVersion.HTTP_1_1)
.bodyString("Important stuff", ContentType.DEFAULT_TEXT)
.execute().returnContent().asBytes();
具体案例:
package com.my.httpclient;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.StringEntity;
public class FluentDemo {
public static void main(String[] args) {
try {
String text = Request.Get("http://httpbin.org/get").execute().returnContent().toString();
System.out.println(text);
String data = "username:vip,password:secret";
StringEntity se = new StringEntity(data);
String result = Request.Post("http://httpbin.org/post")
// .addHeader("Host", "my.worktile.com")
// .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0")
// .addHeader("Accept", "application/json, text/plain, */*")
// .addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
// .addHeader("Accept-Encoding", "gzip, deflate, br")
// .addHeader("Content-Type", "application/json;charset=utf-8")
// .addHeader("Connection", "keep-alive")
.body(se).execute().returnContent().asString();
System.out.println(result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果:
老用法实例一:
package com.my.httpclient;
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.HttpGet;
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 BaseOldTest {
public static void mian(String[] args) {
get();
post();
}
public static void get() {
CloseableHttpClient chc = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://httpbin.org/get");
CloseableHttpResponse response1 = null;
try {
response1 = chc.execute(httpGet);
System.out.println(response1);
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
EntityUtils.consume(entity1);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
response1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void post() {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://httpbin.org/post");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
CloseableHttpResponse response2 = null;
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
response2 = httpclient.execute(httpPost);
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
EntityUtils.consume(entity2);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
response2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
老用法实例二:
package com.my.httpclient;
import java.io.IOException;
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 BaseOldTest2 {
public static void main(String[] args) throws IOException {
System.out.println(getRequest("http://api.map.baidu.com/place/v2/search?query=银行&bounds=39.915,116.404,39.975,116.414&output=json&ak="));
}
public static String getRequest(String p_request) throws IOException{
CloseableHttpClient httpclient;
CloseableHttpResponse response;
HttpGet httpget;
httpclient = HttpClients.createDefault();
httpget = new HttpGet(p_request);
response = httpclient.execute(httpget);
return response.toString();
}
}