一开始上手就用4.5有的不大习惯,看到的教程和分享都是4.5之前的,这个纪录主要是把掉过的坑都记住。
1.HttpGet返回网页信息
package cn.limbo.grabdata.test;
import org.apache.http.HttpEntity;
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;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by Limbo on 16/7/28.
*/
public class TestHttpClient {
public static void main(String[] args) {
//4.x版本貌似HttpClient就成了一个接口了
//现在都用这个来创建客户端连接,相当于打开了一个浏览器
CloseableHttpClient httpClient = HttpClients.createDefault();
//以前的名字叫做GetMethod,现在改名为HttpGet
HttpGet httpGet = new HttpGet("http://www.baidu.com");
//返回请求信息
System.out.println("Executing request" + httpGet.getRequestLine());
//创建一个返回信息的对象
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
try {
System.out.println("-------------------");
//打印返回状态
System.out.println(response.getStatusLine());
//实体
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
InputStream inputStream = httpEntity.getContent();
try {
inputStream.read();
} catch (IOException ex) {
throw ex;
} finally {
inputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.HttpGet
package cn.limbo.grabdata.test;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.impl.conn.DefaultHttpClientConnectionOperator;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Limbo on 16/7/29.
*/
public class TestPost {
public static void main(String[] args) {
CloseableHttpClient client = HttpClients.createDefault();
try {
//一定要加上http否则会报 Target host is not specified
HttpPost httpPost = new HttpPost("http://www.baidu.com");
//设置HttpPost的传参数
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("post", "I will post"));
//由于JDK7出现,HTTP中的很多编码被标识成了过期,使用StandardCharsets里面的预定义的东西
httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
CloseableHttpResponse response = client.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("statusCode : " + statusCode);
String responseStr = null;
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
responseStr = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);
}
System.out.println("respStr = " + responseStr);
//释放资源
EntityUtils.consume(httpEntity);
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.补充
1.需要向服务器发送请求,我们需要一个org.apache.http.client.HttpClient
的实例对象,一般使用的都是org.apache.http.impl.client.CloseableHttpClient
,创建该对象的最简单方法是CloseableHttpClient client = HttpClients.createDefault();
,HttpClients是负责创建CloseableHttpClient的工厂,现在我们用最简单的方法就是使用默认配置去创建实例,后面我们再讨论有参数定制需求的实例创建方法。我们可以通过打断点的方式看到这个默认的实例对象的连接管理器 : org.apache.http.conn.HttpClientConnectionManager
、请求配置 : org.apache.http.client.config.RequestConfig
等配置的默认参数,这些都是后面需要了解的。
2.构造请求方法HttpPost post = new HttpPost(url);
表示我们希望用那种交互方法与服务器交互,HttpClient为每种交互方法都提供了一个类:HttpGet,
HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, 还有 HttpOptions。
3.向服务器提交请求CloseableHttpResponse response = client.execute(post);
,很明显`CloseableHttpResponse就是用了处理返回数据的实体,通过它我们可以拿到返回的状态码、返回实体等等我们需要的东西。
4.EntityUtils是官方提供一个处理返回实体的工具类,toString方法负责将返回实体装换为字符串,官方是不太建议使用这个类的,除非返回数据的服务器绝对可信和返回的内容长度是有限的。官方建议是自己使用HttpEntity#getContent()或者HttpEntity#writeTo(OutputStream),需要提醒的是记得关闭底层资源。
5.EntityUtils.consume(entity);
负责释放资源,通过源码可知,是需要把底层的流关闭:
InputStream instream = entity.getContent();
if (instream != null) {
instream.close();
}