您的位置:首页 > 理论基础 > 计算机网络

HttpClient4.3.1简单入门实例 转

2015-02-03 16:41 211 查看
public class HttpClientTest {

public static void main(String args[]) {

//创建HttpClientBuilder

HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

//HttpClient

CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

HttpGet httpGet = new HttpGet("http://www.gxnu.edu.cn/default.html");

System.out.println(httpGet.getRequestLine());

try {

//执行get请求

HttpResponse httpResponse = closeableHttpClient.execute(httpGet);

//获取响应消息实体

HttpEntity entity = httpResponse.getEntity();

//响应状态

System.out.println("status:" + httpResponse.getStatusLine());

//判断响应实体是否为空

if (entity != null) {

System.out.println("contentEncoding:" + entity.getContentEncoding());

System.out.println("response content:" + EntityUtils.toString(entity));

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

public class HttpClientTest {
public static void main(String args[]) {
//创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

HttpGet httpGet = new HttpGet("http://www.gxnu.edu.cn/default.html");
System.out.println(httpGet.getRequestLine());
try {
//执行get请求
HttpResponse httpResponse = closeableHttpClient.execute(httpGet);
//获取响应消息实体
HttpEntity entity = httpResponse.getEntity();
//响应状态
System.out.println("status:" + httpResponse.getStatusLine());
//判断响应实体是否为空
if (entity != null) {
System.out.println("contentEncoding:" + entity.getContentEncoding());
System.out.println("response content:" + EntityUtils.toString(entity));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {


[java] view plaincopyprint?





//关闭流并释放资源

closeableHttpClient.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

//关闭流并释放资源
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


以下内容来自HttpClient4.3.1 API文档:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/overview-summary.html

2、HttpClientBuilder

HttpClientBuilder用于创建CloseableHttpClient实例。看了一下API文档,AbstractHttpClientAutoRetryHttpClientDefaultHttpClient等都被弃用了,使用HttpClientBuilder代替。

3、CloseableHttpClient

实现接口:Closeable, AutoCloseable, HttpClient;子类:AbstractHttpClient

4、HttpGet

非线程安全;HttpGet有三个构造方法:HttpGet()、HttpGet(String uri)、HttpGet(URI uri)

5、HttpResponse

服务器在接收和解释请求之后返回一个HTTP响应信息

Response      = Status-Line
*(( general-header
| response-header
| entity-header ) CRLF)
CRLF
[ message-body ]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: