使用HttpClient进行远程接口测试

前两天在工作中,项目组长给我了一个远程接口让我给测一下,因为是http协议,所以我首先想到了用httpClient工具类来测试,网上一查,找到了好多示例代码,随便复制了一个demo进行了简单的修改,结果怎么测试都是连接超时,试了很多个demo也不好使,最后发现是因为我们公司访问外网是通过代理,所以在进行测试的时候需要配置代理。一下是我的测试程序

用到的jar包:

 1 package com.lym.test;
 2 
 3 import org.apache.http.HttpEntity;
 4 import org.apache.http.HttpHost;
 5 import org.apache.http.client.config.RequestConfig;
 6 import org.apache.http.client.methods.CloseableHttpResponse;
 7 import org.apache.http.client.methods.HttpPost;
 8 import org.apache.http.entity.StringEntity;
 9 import org.apache.http.impl.client.CloseableHttpClient;
10 import org.apache.http.impl.client.HttpClientBuilder;
11 import org.apache.http.util.EntityUtils;
12 
13 import com.google.gson.JsonObject;
14 
15 public class HttpClientTest {
16     
17     public static void main(String args[]) throws Exception {
18         
19         // 创建HttpClientBuilder
20         HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
21         // HttpClient
22         CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
23         // 依次是目标请求地址,端口号,协议类型
24         HttpHost target = new HttpHost("61.144.244.6:8888/sztmerchant/merchant/addIsztMerchant.htm", 8888, "http");
25         // 依次是代理地址,代理端口号,协议类型
26         HttpHost proxy = new HttpHost("proxy3.bj.petrochina", 8080, "http");
27         RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
28 
29         // 请求地址
30         HttpPost httpPost = new HttpPost("http://61.144.244.6:8888/sztmerchant/merchant/addIsztMerchant.htm");
31         // 设置头信息
32         httpPost.addHeader("Content-type", "application/json; charset=utf-8");
33         httpPost.setHeader("Accept", "application/json");
34         httpPost.setConfig(config);
35         
36         // 创建参数json串
37         JsonObject jsonObj = new JsonObject();
38         jsonObj.addProperty("merchantNo", "33300911238");
39         jsonObj.addProperty("merchantName", "电商运营生产测试1238");
40         String jsonStr = jsonObj.toString();
41         System.out.println("parameters: " + jsonStr);
42         
43         StringEntity entity;
44         try {
45             entity = new StringEntity(jsonStr, "UTF-8");
46             httpPost.setEntity(entity);
47             CloseableHttpResponse response = closeableHttpClient.execute(target, httpPost);
48             // getEntity()
49             HttpEntity httpEntity = response.getEntity();
50             if (httpEntity != null) {
51                 // 打印响应内容
52                 System.out.println("result: " + EntityUtils.toString(httpEntity, "UTF-8"));
53             }else {
54                 System.out.println("无响应内容");
55             }
56             // 释放资源
57             if(closeableHttpClient != null) {
58                 closeableHttpClient.close();                
59             }
60         } catch (Exception e) {
61             e.printStackTrace();
62         }
63     }
64     
65 }

 

posted @ 2016-01-21 13:53  刘彦民  阅读(2136)  评论(0编辑  收藏  举报