zoukankan      html  css  js  c++  java
  • SpringBoot使用HttpClient远程调用

    一.  Get请求

    try {
                //拼接url
                url = url+"access_token="+token+"&department_id=1&fetch_child=1";
                //解决证书明匹配问题
                SSLSocketFactory.getSocketFactory().setHostnameVerifier(new     
                        AllowAllHostnameVerifier());
                //根据地址获取请求
                HttpGet request = new HttpGet(url);
                //获取当前客户端对象
                HttpClient httpClient = new DefaultHttpClient();
                //通过请求获取相应对象
                HttpResponse response = httpClient.execute(request);
                // 判断网络连接状态码是否正常(0--200都数正常)
                String result=null;
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    result= EntityUtils.toString(response.getEntity(),"utf-8");
                }    
    
    } catch (Exception e) {
           e.printStackTrace();
     }                           

    二.  Post请求

     try{
            String url = userMapper.getValue(urlId);
            url = url + "access_token=" + token;
            //主机证书明不匹配问题
            SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());

         //获取请求地址 HttpPost post
    = new HttpPost(url);
         //获取当前客户端对象 HttpClient httpClient
    = new DefaultHttpClient(); // 设置超时时间 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);      //设置参数 StringEntity s = new StringEntity(jsonObject.toString()); s.setContentEncoding("UTF-8"); s.setContentType("application/json"); post.setEntity(s);      //通过请求获得相应的对象    HttpResponse res = client.execute(post);
         //判断是否成功
         if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
        HttpEntity entity = res.getEntity();
        String result = EntityUtils.toString(res.getEntity());// 返回json格式:
        }
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
  • 相关阅读:
    【t066】致命的珠宝
    【t081】序列长度
    【t081】序列长度(贪心做法)
    【t093】外星密码
    【codeforces 761A】Dasha and Stairs
    【codeforces 761B】Dasha and friends
    【codeforces 761C】Dasha and Password(动态规划做法)
    【codeforces 761C】Dasha and Password(贪心+枚举做法)
    【codeforces 761D】Dasha and Very Difficult Problem
    【u224】传送机
  • 原文地址:https://www.cnblogs.com/gxlaqj/p/10335400.html
Copyright © 2011-2022 走看看