httpComponents发送get请求并获取响应信息

试了一把httpComponents,httpComponents发送get请求并获取响应信息并输出状态码

首先将下载的httpcomponents-client压缩包解压,其中lib文件夹下的jar全部Add External Jars,java源码如下:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class http {

public static void main(String[] args) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet Get = new HttpGet(” http://6san.com”);
//创建HttpGet实例
HttpResponse response1 = httpClient.execute(Get);
//使用HttpClient发送get请求,获得http响应HttpResponse

try {
System.out.println(response1.getStatusLine());
//输出http响应的状态行
HttpEntity entity1 = response1.getEntity();
EntityUtils.consume(entity1);
} finally {
Get.releaseConnection();
}

}

}

httpComponents获得http请求响应码和http协议版本号的方法

response1.getStatusLine().getStatusCode() == 200

getProtocolVersion(): 得到请求协议和协议版本号,如HTTP/1.0
getStatusCode():得到响应码,如200

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注