当前位置: 首页 > news >正文

JAVA HttpClient 远程调用接口doGet、doPost工具类

可以用于远程调用POST方式接口,GET方式接口,且里面包括了跳过SSL验证方法 。

并且在常用的方法下,有注释掉的调用举例:

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpsUtils {
   
   /**
    * 常用的GET方式
    * get (@RequestParam("vin")String vin可以接收)
    * 
    * @param host
    * @param path
    * @param headers
    * @param querys
    * @return
    * @throws Exception
    */
   public static HttpResponse doGet(String host, String path,
                                     Map<String, String> headers,
                                     Map<String, String> querys)
            throws Exception {     
       HttpClient httpClient = wrapClient(host);

       HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
           request.addHeader(e.getKey(), e.getValue());
        }
        
        return httpClient.execute(request);
    }

   /**
    * 调用例子 doGet
    */
// @GetMapping("/doGetTest")
// public  String doGetTest() throws Exception {
//    String IP = "http://localhost:8075";
//    String path="/testTest";
//    Map<String, String> headers = new HashMap<String, String>();
//    //headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//    Map<String, String> querys = new HashMap<String, String>();
//    querys.put("vin","VIN223333");
//    querys.put("sn","SN666666666");
//    HttpResponse response = HttpsUtils.doGet(IP, path, headers, querys);
//    得到返回的参数
//    String  getResponse = EntityUtils.toString(response.getEntity());
//
//    return getResponse;
// }


   /**
    *  常用的Post方式
    *  Post String (传递json格式的String,@RequestBody String testData 可以接收)
    * 对于得到参数格式为:{"vin":"VIN223333","sn":"SN666666666"}
    * @param host
    * @param path
    * @param method
    * @param headers
    * @param querys
    * @param body
    * @return
    * @throws Exception
    */
   public static HttpResponse doPost(String host, String path, String method,
                             Map<String, String> headers,
                             Map<String, String> querys,
                             String body)
         throws Exception {
      HttpClient httpClient = wrapClient(host);

      HttpPost request = new HttpPost(buildUrl(host, path, querys));
      for (Map.Entry<String, String> e : headers.entrySet()) {
         request.addHeader(e.getKey(), e.getValue());
      }

      if (StringUtils.isNotBlank(body)) {
         request.setEntity(new StringEntity(body, "utf-8"));
      }

      return httpClient.execute(request);
   }

   /**
    * 调用例子 doPost
    */
// @PostMapping("/doPostTest")
// public  String doPostTest() throws Exception {
//    String IP = "http://localhost:8075";
//    String path="/testPostTest";
//    Map<String, String> headers = new HashMap<String, String>();
//    headers.put("Content-Type", "application/json; charset=UTF-8");
//    Map<String, String> querys = new HashMap<String, String>();
//
//    Map<String, String> bodys = new HashMap<String, String>();
//    bodys.put("vin","VIN223333");
//    bodys.put("sn","SN666666666");
//    String jsonStr= JSONObject.toJSONString(bodys);
//
//    HttpResponse response = HttpsUtils.doPost(IP, path,"POST", headers, querys,jsonStr);
//    得到返回的参数
//      String  getResponse = EntityUtils.toString(response.getEntity());
//
//    return getResponse;
// }



   /**
    * basic auth认证 Get方式
    */
   public static String doGetWithBasicAuth(String url, String basic_userName, String basic_password) throws IOException {

      // 创建HttpClientBuilder
      HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
      // 设置BasicAuth
      CredentialsProvider provider = new BasicCredentialsProvider();
      // Create the authentication scope
      AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
      // Create credential pair,在此处填写用户名和密码
      UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(basic_userName, basic_password);
      // Inject the credentials
      provider.setCredentials(scope, credentials);
      // Set the default credentials provider
      httpClientBuilder.setDefaultCredentialsProvider(provider);
      // HttpClient
      CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

      String result = "";
      HttpGet httpGet = null;
      HttpResponse httpResponse = null;
      HttpEntity entity = null;

      httpGet = new HttpGet(url);
      try {
         httpResponse = closeableHttpClient.execute(httpGet);
         entity = httpResponse.getEntity();
         if (entity != null) {
            result = EntityUtils.toString(entity);
         }
      } catch (ClientProtocolException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }

      // 关闭连接
      closeableHttpClient.close();


      return result;
   }

   /**
    * 调用举例
    */
// String url = "http://140.xxx.22.xxx:18089/apxxx/" + vin;
// //basic auth中的用户名和密码
// String basic_userName = "admin";
// String basic_password = "public";
// 得到返回的参数
// String resultStr = HttpClientUtilCIV.doGetWithBasicAuth(url, basic_userName, basic_password);


   /**
    * post form(传递的是用&符号连接的字符串,@RequestBody String testData可以接收)
    *  对于得到参数格式为:vin=111&sn=12335
    * @param host
    * @param path
    * @param headers
    * @param querys
    * @param bodys
    * @return
    * @throws Exception
    */
   public static HttpResponse doPost(String host, String path,
                             Map<String, String> headers,
                             Map<String, String> querys,
                             Map<String, String> bodys)
         throws Exception {
      HttpClient httpClient = wrapClient(host);

      HttpPost request = new HttpPost(buildUrl(host, path, querys));
      for (Map.Entry<String, String> e : headers.entrySet()) {
         request.addHeader(e.getKey(), e.getValue());
      }

      if (bodys != null) {
         List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

         for (String key : bodys.keySet()) {
            nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
         }
         UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
         formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
         request.setEntity(formEntity);
      }

      return httpClient.execute(request);
   }





   /**
    * Post stream
    * 
    * @param host
    * @param path
    * @param method
    * @param headers
    * @param querys
    * @param body
    * @return
    * @throws Exception
    */
   public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      byte[] body)
            throws Exception {     
       HttpClient httpClient = wrapClient(host);

       HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
           request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
           request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }
   
   /**
    * Put String
    * @param host
    * @param path
    * @param method
    * @param headers
    * @param querys
    * @param body
    * @return
    * @throws Exception
    */
   public static HttpResponse doPut(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     String body)
            throws Exception {     
       HttpClient httpClient = wrapClient(host);

       HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
           request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
           request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }
   
   /**
    * Put stream
    * @param host
    * @param path
    * @param method
    * @param headers
    * @param querys
    * @param body
    * @return
    * @throws Exception
    */
   public static HttpResponse doPut(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     byte[] body)
            throws Exception {     
       HttpClient httpClient = wrapClient(host);

       HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
           request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
           request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }
   
   /**
    * Delete
    *  
    * @param host
    * @param path
    * @param method
    * @param headers
    * @param querys
    * @return
    * @throws Exception
    */
   public static HttpResponse doDelete(String host, String path, String method,
                                        Map<String, String> headers,
                                        Map<String, String> querys)
            throws Exception {     
       HttpClient httpClient = wrapClient(host);

       HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
           request.addHeader(e.getKey(), e.getValue());
        }
        
        return httpClient.execute(request);
    }



   @SuppressWarnings("resource")
   public static String doPost(String host, String path,String jsonstr,String charset){
        String url=host+path;
      HttpClient httpClient = null;
      HttpPost httpPost = null;
      String result = null;
      try{
       httpClient = wrapClient(host);

//------------------------------4.1,4.2 版本设置时间-----------------------------

         //设置连接时间
         httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
         //设置数据传输时间
         httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);

         httpPost = new HttpPost(url);
         httpPost.addHeader("Content-Type", "application/json");

         //此处是将请求体封装成为了StringEntity,若乱码则指定utf-8
         //StringEntity se = new StringEntity(jsonstr,"utf-8");
         StringEntity se = new StringEntity(jsonstr);
         se.setContentType("text/json");
         se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
         httpPost.setEntity(se);
         HttpResponse response = httpClient.execute(httpPost);

         if(response != null){
            HttpEntity resEntity = response.getEntity();
            if(resEntity != null){
               result = EntityUtils.toString(resEntity,charset);
            }
         }
      }catch(Exception ex){
//            ex.printStackTrace();
         //连接超时或者数据传输时间超时
         String apiResult="timeOut";
         return  apiResult;
      }
      return result;
   }

   /**
    *doPost 举例
    */

//    String IP = "http://localhost:8075";
//    String path="/testPostTest";
//    Map<String, String> bodys = new HashMap<String, String>();
//    bodys.put("vin","VIN223333");
//    bodys.put("sn","SN666666666");
//    String jsonStr= JSONObject.toJSONString(bodys);
//    String resultStr= HttpsUtils.doPost(IP,path,jsonStr, "utf-8");
//    return resultStr;
// }


   /**
    * 拼接url
    * @param host
    * @param path
    * @param querys
    * @return
    * @throws UnsupportedEncodingException
    */
   private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
       StringBuilder sbUrl = new StringBuilder();
       sbUrl.append(host);
       if (!StringUtils.isBlank(path)) {
          sbUrl.append(path);
        }
       if (null != querys) {
          StringBuilder sbQuery = new StringBuilder();
           for (Map.Entry<String, String> query : querys.entrySet()) {
              if (0 < sbQuery.length()) {
                 sbQuery.append("&");
              }
              if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                 sbQuery.append(query.getValue());
                }
              if (!StringUtils.isBlank(query.getKey())) {
                 sbQuery.append(query.getKey());
                 if (!StringUtils.isBlank(query.getValue())) {
                    sbQuery.append("=");
                    sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                 }                
                }
           }
           if (0 < sbQuery.length()) {
              sbUrl.append("?").append(sbQuery);
           }
        }
       
       return sbUrl.toString();
    }
   
   private static HttpClient wrapClient(String host) {
      HttpClient httpClient = new DefaultHttpClient();
      if (host.startsWith("https://")) {
         sslClient(httpClient);
      }
      
      return httpClient;
   }

   private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                @Override
                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                   
                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }

            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
           throw new RuntimeException(ex);
        }
    }



 接下来这个工具类是post请求,里面有关于设置BASEAUTH 认证的,


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.Base64;


/**
 * @Author:JCccc
 * @Description:
 * @Date: created in 15:21 2019/4/11
 */
public class HttpUtil {


    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[]{trustManager}, null);
        return sc;
    }


    public static String doPost(String url, String jsonstr,String username,String password) {
        String result = null;
        try {
            String body = "";
            //采用绕过验证的方式处理https请求
            SSLContext sslcontext = createIgnoreVerifySSL();

            // 设置协议http和https对应的处理socket链接工厂的对象
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", new SSLConnectionSocketFactory(sslcontext))
                    .build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            HttpClients.custom().setConnectionManager(connManager);

            //创建自定义的httpclient对象
            CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connManager).build();
            //	CloseableHttpClient client = HttpClients.createDefault();

            //创建post方式请求对象
            HttpPost httpPost = null;
            result = null;
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json");

            //  basic auth认证

            httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));

            StringEntity se = new StringEntity(jsonstr);
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            httpPost.setEntity(se);
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            // HttpResponse response = httpClient.execute(httpPost);

            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }

            // 关闭连接
            closeableHttpClient.close();
        } catch (NoSuchAlgorithmException | KeyManagementException | IOException | ParseException e) {
            e.printStackTrace();
        }

        return result;
    }

}

 

相关文章:

  • JAVA 接口签名sign生成 工具类
  • mybatis-config配置文件各项简单介绍
  • Springboot整合Mybatis增删查改、连接MYSQL数据库及配置druid连接池
  • JAVA 模板设计模式
  • Springboot 最简单的结合MYSQL数据实现EXCEL表格导出及数据导入
  • Springboot中使用GSON报错 An attempt was made to call the method com.google.gson.GsonBuilder.setLenient
  • IDEA @AutoWired注入bean 出现红色波浪线
  • JAVA 最常用实用的正则表达式校验
  • Springboot 整合WebFlux 实现RESTFUI风格API 及简单的CRUD
  • Springboot 读取配置文件application.properties (yml)的四种方式
  • Springboot 指定获取自己写的配置properties文件的值
  • JAVA AES加密解密工具类
  • Springboot 快速了解 事务回滚@Transactional
  • Springboot Mybatis使用pageHelper实现分页查询
  • JAVA 雪花算法 唯一ID生成工具类
  • 时间复杂度分析经典问题——最大子序列和
  • 「译」Node.js Streams 基础
  • Computed property XXX was assigned to but it has no setter
  • Dubbo 整合 Pinpoint 做分布式服务请求跟踪
  • HTML5新特性总结
  • JavaScript 无符号位移运算符 三个大于号 的使用方法
  • javascript数组去重/查找/插入/删除
  • js继承的实现方法
  • PHP 的 SAPI 是个什么东西
  • Python socket服务器端、客户端传送信息
  • Spark in action on Kubernetes - Playground搭建与架构浅析
  • SQLServer之创建数据库快照
  • Tornado学习笔记(1)
  • VirtualBox 安装过程中出现 Running VMs found 错误的解决过程
  • 初识MongoDB分片
  • 大快搜索数据爬虫技术实例安装教学篇
  • 跨域
  • 如何优雅的使用vue+Dcloud(Hbuild)开发混合app
  • 使用权重正则化较少模型过拟合
  • 世界上最简单的无等待算法(getAndIncrement)
  • 主流的CSS水平和垂直居中技术大全
  • 【云吞铺子】性能抖动剖析(二)
  • 基于django的视频点播网站开发-step3-注册登录功能 ...
  • 扩展资源服务器解决oauth2 性能瓶颈
  • #我与Java虚拟机的故事#连载15:完整阅读的第一本技术书籍
  • #在线报价接单​再坚持一下 明天是真的周六.出现货 实单来谈
  • (C语言)输入自定义个数的整数,打印出最大值和最小值
  • (附源码)springboot高校宿舍交电费系统 毕业设计031552
  • (十六)串口UART
  • (算法)前K大的和
  • (转)PlayerPrefs在Windows下存到哪里去了?
  • . Flume面试题
  • .Net Core 中间件验签
  • .NET Core日志内容详解,详解不同日志级别的区别和有关日志记录的实用工具和第三方库详解与示例
  • .net 生成二级域名
  • .NET程序员迈向卓越的必由之路
  • .pop ----remove 删除
  • @Autowired自动装配
  • @reference注解_Dubbo配置参考手册之dubbo:reference
  • [ 云计算 | AWS 实践 ] 基于 Amazon S3 协议搭建个人云存储服务