HttpClient post请求 第三方接口验证 发送参数 请求报文头和报文体

1     HttpClient client = HttpClientUtils.getConnection();//得到client

 HttpUriRequest post = HttpClientUtils.getRequestMethodNew(map, chekUserLoginUrl, "post",authorization,time);

//通过此接口拼接报文

2  //拼接报文 +参数设置。

    private static PoolingHttpClientConnectionManager connectionManager = null;
    private static HttpClientBuilder httpBulder = null;
    private static RequestConfig requestConfig = null;
    private static int MAXCONNECTION = 20;
    private static int DEFAULTMAXCONNECTION = 5;
    private static String IP = "*";
    private static int PORT = 0;
    static {
        //设置http的状态参数
        requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();
        HttpHost target = new HttpHost(IP, PORT);
        connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(MAXCONNECTION);
        connectionManager.setDefaultMaxPerRoute(DEFAULTMAXCONNECTION);
        connectionManager.setMaxPerRoute(new HttpRoute(target), 20);
        httpBulder = HttpClients.custom();
        httpBulder.setConnectionManager(connectionManager);
    }
    public static CloseableHttpClient getConnection() {
        CloseableHttpClient httpClient = httpBulder.build();
        httpClient = httpBulder.build();
        return httpClient;
    }

 public static HttpUriRequest getRequestMethodNew(Map<String, String> map, String url, String method,String authorization,String time) throws Exception, IOException {

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, String>> entrySet = map.entrySet();
        for (Map.Entry<String, String> e : entrySet) {
            String name = e.getKey();
            String value = e.getValue();
            NameValuePair pair = new BasicNameValuePair(name, value);
            params.add(pair);
        }
        url.replaceAll(" ","");
        HttpUriRequest reqMethod = null;

if ("post".equals(method)) {

//报文体方法1

/* reqMethod = RequestBuilder.post().setUri(url)
.addParameters(params.toArray(new BasicNameValuePair[params.size()]))
.setConfig(requestConfig).build();*/
System.out.println("开始写psot报文 主体和头部");
/* 体 */
 JSONObject jsonParam = new JSONObject();  
 JSONObject jsonParam1 = new JSONObject();  
/*  List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>(); 
 formParams.add(new BasicNameValuePair("username", map.get("username")));
 formParams.add(new BasicNameValuePair("password",map.get("password"))); 
 formParams.add(new BasicNameValuePair("appId", map.get("appId")));
 formParams.add(new BasicNameValuePair("userIP",map.get("userIP"))); 

 formParams.add(new BasicNameValuePair("userClient", map.get("userClient")));*/

//报文体方法2 其中方法的body是以json的格式。

 jsonParam.put("username", map.get("username"));
 jsonParam.put("password",map.get("password")); 
 jsonParam.put("appId", map.get("appId"));
 jsonParam.put("userIP",map.get("userIP")); 
 jsonParam.put("userClient", map.get("userClient"));
 StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//非json格式直接放入formParams
 entity.setContentEncoding("UTF-8");    
              entity.setContentType("application/json"); 
 reqMethod =RequestBuilder.post().setUri(url).setEntity(entity).setConfig(requestConfig).build();
/* 头 */
/*  Map<String,String> aHeaders  = new HashMap<String,String>();
 JSONArray array = new JSONArray();
 List<Headers>  aHeaders2  = new ArrayList<Headers>();*/
/*  aHeaders.put("User-Agent",map.get("userClient"));
 aHeaders.put("Accept-Language","en-US,en;q=0.5");
 aHeaders.put("Accept-Encoding","gzip, deflate");
 aHeaders.put("Content-Type","application/json; charset=utf-8");
 aHeaders.put("Authorization",authorization);
 aHeaders.put("x-idm-date",time);
 array.add(aHeaders);
 reqMethod.setHeader((org.apache.http.Header) array);*/


   reqMethod.setHeader("User-Agent", map.get("userClient")); 
reqMethod.setHeader("accept", "application/json, text/plain, */*"); 
reqMethod.setHeader("Accept-Language", "en-US,en;q=0.5");
reqMethod.setHeader("Accept-Encoding", "gzip, deflate");
reqMethod.setHeader("Content-Type", "application/json; charset=utf-8");
    reqMethod.setHeader("connection", "Keep-Alive"); 


reqMethod.setHeader("Authorization", authorization);// 数字签名
reqMethod.setHeader("x-idm-date", time);// 调用时间
System.out.println("头部结束------");
} else if ("get".equals(method)) {
            reqMethod = RequestBuilder.get().setUri(url)
                    .addParameters(params.toArray(new BasicNameValuePair[params.size()]))
                    .setConfig(requestConfig).build();
        }
        return reqMethod;

    }


3   接上面的1-----HttpResponse response = client.execute(post);
        System.out.println("得到response----------"+response);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            String obj = EntityUtils.toString(entity, "utf-8");
            if(StringUtils.isEmpty(obj)){
            throw new CheckUserTPException("系统错误:身份平台验证失败1");
            }else{
            CheckUserLoginPio user = JSONObject.parseObject(obj, CheckUserLoginPio.class);
            if(StringUtils.isEmpty(user.getCode()) || StringUtils.isEmpty(user.getMessage())){
            throw new CheckUserTPException("测:未返回报文");
            }else 
            if(!user.getCode().equals("0")){
            String message =user.getMessage();
                throw new CheckUserTPException(message+"dddddd");
                }
                else{
                isCheck = true;
                }
            }
            
        } else {
        //throw new CheckUserTPException("系统错误:身份平台验证失败2");
          //post.abort();
        int aString = response.getStatusLine().getStatusCode();
        throw new CheckUserTPException(aString+"状态码"+ HttpStatus.SC_OK);
        }
        return isCheck;

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于高并发请求第三方接口,可以使用 HttpClient 来实现。以下是一些实践中的建议: 1. 使用连接池:在高并发环境下,创建和关闭连接会消耗大量资源和时间。使用连接池可以重复利用连接,提高性能。HttpClient 提供了连接池管理器,可以通过 PoolingHttpClientConnectionManager 类来管理连接池。 2. 设置超时时间:在请求第三方接口时,应该设置合理的超时时间。如果接口响应时间过长,应该及时中断请求,防止占用过多资源。可以通过 RequestConfig 类的 setConnectTimeout 和 setSocketTimeout 方法来设置连接和读取超时时间。 3. 并发执行请求:可以使用多线程或线程池来并发执行请求。每个线程可独立创建 HttpClient 实例,并使用独立的连接池进行请求。这样可以提高并发能力,同时注意要控制并发线程数量,避免对第三方接口造成过大的负载。 4. 考虑流量控制:高并发请求可能导致第三方接口的压力过大,可能会被服务提供方限制流量或拒绝服务。可以通过限制每秒请求的数量、使用消息队列等方式来控制流量,避免对第三方接口造成过大的压力。 5. 错误处理和重试机制:在请求第三方接口时,要考虑网络异常、超时、返回错误码等情况。可以通过捕获异常并进行重试,或者根据返回的错误码进行相应的处理。 综上所述,使用 HttpClient 可以方便地实现高并发请求第三方接口,并根据实际情况进行连接池管理、设置超时时间、并发执行请求、流量控制以及错误处理和重试等操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值