Java之使用HttpClient发送GET请求

 1 package LoadRunner;
 2 
 3 import org.apache.http.HttpEntity;
 4 import org.apache.http.HttpResponse;
 5 import org.apache.http.client.methods.HttpGet;
 6 import org.apache.http.impl.client.CloseableHttpClient;
 7 import org.apache.http.impl.client.HttpClients;
 8 
 9 import java.io.BufferedReader;
10 
11 import java.io.InputStreamReader;
12 
13 /*
14 * 使用Apache的HttpClient发送GET和POST请求的步骤如下:
15 *   1. 使用帮助类HttpClients创建CloseableHttpClient对象.
16 *   2. 基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例.
17 *   3. 使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.
18 *   4. 对于POST请求,创建NameValuePair列表,并添加所有的表单参数.然后把它填充进HttpPost实体.
19 *   5. 通过执行此HttpGet或者HttpPost请求获取CloseableHttpResponse实例
20 *   6. 从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.
21 *   7. 最后关闭HttpClient资源.
22 * */
23 
24 /**
25  * 使用HttpClient调用接口
26  * 为性能测试写接口脚本
27  */
28 public class GetChannelLine {
29     public static void main(String args[]) throws Exception {
30         String channelId = "sdd";
31         String clientId = "123";
32         // 目标地址
33         String url = "http://XXX.XXX.com.cn/arowana/channel/getChannelLine?channelId=" + channelId + "&clientId=" + clientId;
34         HttpGet httpGet = new HttpGet(url);
35 
36         // 设置类型 "application/x-www-form-urlencoded" "application/json"
37         httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
38         System.out.println("调用URL: " + httpGet.getURI());
39 
40 //        httpClient实例化
41         CloseableHttpClient httpClient = HttpClients.createDefault();
42         // 执行请求并获取返回
43         HttpResponse response = httpClient.execute(httpGet);
44 //        System.out.println("Response toString()" + response.toString());
45         HttpEntity entity = response.getEntity();
46         System.out.println("返回状态码:" + response.getStatusLine());
47 
48         //得到返回数据的长度;没有该参数返回-1
49 //        if (entity != null) {
50 //            System.out.println("返回消息内容长度: " + entity.getContentLength());
51 //        }
52 
53         // 显示结果
54         BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
55         String line = null;
56         StringBuffer responseSB = new StringBuffer();
57         while ((line = reader.readLine()) != null) {
58             responseSB.append(line);
59         }
60         System.out.println("返回消息:" + responseSB);
61         reader.close();
62 
63         httpClient.close();
64     }
65 }

依赖包:

1         <dependency>
2             <groupId>org.apache.httpcomponents</groupId>
3             <artifactId>httpclient</artifactId>
4             <version>4.5.5</version>
5         </dependency>
原文地址:https://www.cnblogs.com/gongxr/p/8379176.html