参考:
1. Apache Httpclient tutorial
2. Jar包下载
Apache Httpclient 是由apchae提供的http实现。虽然jdk的 java.net包提供了 HttpUrlconnection,但是功能和灵活性都有所欠缺。而apache httclient在效率和功能上有更好的表现。
使用httpclient,需要先到apache网站下载对应的jar包(下载地址)。使用到的jar包有:httpclient-xxx.jar, httpcore-xxx.jar, commons-logging-xxx.jara 等 (XXX为版本号,如httpclient-4.5.6.jar)
以下为实现get和post请求的简单实现:
Http GET
public void testGet() {
// 根据经纬度获取地址
HttpClient httpClient = HttpClients.createDefault();
String url = "http://gc.ditu.aliyun.com/regeocoding?l=34.267673,117.305076&type=111";
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpGet);
// 解析返回数据
parse(response.getEntity().getContent(), "UTF-8");
} catch (IOException ex) {
}
}
Http POST
public void testPost() {
// 获取手机号归属地信息
try {
String url = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
// Post参数
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("tel", "18951848769"));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
// 解析返回数据
//parse(response.getEntity().getContent(), "GB2312");
} catch (Exception ex) {
}
}