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

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