Java之使用HttpClient发送GET请求

时间:2023-03-08 22:40:39
Java之使用HttpClient发送GET请求
 package LoadRunner;

 import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import java.io.BufferedReader; import java.io.InputStreamReader; /*
* 使用Apache的HttpClient发送GET和POST请求的步骤如下:
* 1. 使用帮助类HttpClients创建CloseableHttpClient对象.
* 2. 基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例.
* 3. 使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.
* 4. 对于POST请求,创建NameValuePair列表,并添加所有的表单参数.然后把它填充进HttpPost实体.
* 5. 通过执行此HttpGet或者HttpPost请求获取CloseableHttpResponse实例
* 6. 从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.
* 7. 最后关闭HttpClient资源.
* */ /**
* 使用HttpClient调用接口
* 为性能测试写接口脚本
*/
public class GetChannelLine {
public static void main(String args[]) throws Exception {
String channelId = "sdd";
String clientId = "123";
// 目标地址
String url = "http://XXX.XXX.com.cn/arowana/channel/getChannelLine?channelId=" + channelId + "&clientId=" + clientId;
HttpGet httpGet = new HttpGet(url); // 设置类型 "application/x-www-form-urlencoded" "application/json"
httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
System.out.println("调用URL: " + httpGet.getURI()); // httpClient实例化
CloseableHttpClient httpClient = HttpClients.createDefault();
// 执行请求并获取返回
HttpResponse response = httpClient.execute(httpGet);
// System.out.println("Response toString()" + response.toString());
HttpEntity entity = response.getEntity();
System.out.println("返回状态码:" + response.getStatusLine()); //得到返回数据的长度;没有该参数返回-1
// if (entity != null) {
// System.out.println("返回消息内容长度: " + entity.getContentLength());
// } // 显示结果
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
String line = null;
StringBuffer responseSB = new StringBuffer();
while ((line = reader.readLine()) != null) {
responseSB.append(line);
}
System.out.println("返回消息:" + responseSB);
reader.close(); httpClient.close();
}
}

依赖包:

         <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>