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

简介: 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);
        }
    }
相关文章
|
Java Go 开发工具
【Java】(9)抽象类、接口、内部的运用与作用分析,枚举类型的使用
抽象类必须使用abstract修饰符来修饰,抽象方法也必须使用abstract修饰符来修饰,抽象方法不能有方法体。抽象类不能被实例化,无法使用new关键字来调用抽象类的构造器创建抽象类的实例。抽象类可以包含成员变量、方法(普通方法和抽象方法都可以)、构造器、初始化块、内部类(接 口、枚举)5种成分。抽象类的构造器不能用于创建实例,主要是用于被其子类调用。抽象类中不一定包含抽象方法,但是有抽象方法的类必定是抽象类abstract static不能同时修饰一个方法。
477 1
|
算法 安全 Java
除了类,Java中的接口和方法也可以使用泛型吗?
除了类,Java中的接口和方法也可以使用泛型吗?
360 11
|
存储 缓存 安全
Java集合框架(二):Set接口与哈希表原理
本文深入解析Java中Set集合的工作原理及其实现机制,涵盖HashSet、LinkedHashSet和TreeSet三大实现类。从Set接口的特性出发,对比List理解去重机制,并详解哈希表原理、hashCode与equals方法的作用。进一步剖析HashSet的底层HashMap实现、LinkedHashSet的双向链表维护顺序特性,以及TreeSet基于红黑树的排序功能。文章还包含性能对比、自定义对象去重、集合运算实战和线程安全方案,帮助读者全面掌握Set的应用与选择策略。
1622 23
|
存储 安全 Java
Java集合框架(一):List接口及其实现类剖析
本文深入解析Java中List集合的实现原理,涵盖ArrayList的动态数组机制、LinkedList的链表结构、Vector与Stack的线程安全性及其不推荐使用的原因,对比了不同实现的性能与适用场景,帮助开发者根据实际需求选择合适的List实现。
1476 0
|
数据采集 JSON Java
Java爬虫获取1688店铺所有商品接口数据实战指南
本文介绍如何使用Java爬虫技术高效获取1688店铺商品信息,涵盖环境搭建、API调用、签名生成及数据抓取全流程,并附完整代码示例,助力市场分析与选品决策。
|
安全 Java 开发者
Java集合框架:详解Deque接口的栈操作方法全集
理解和掌握这些方法对于实现像浏览器后退功能这样的栈操作来说至关重要,它们能够帮助开发者编写既高效又稳定的应用程序。此外,在多线程环境中想保证线程安全,可以考虑使用ConcurrentLinkedDeque,它是Deque的线程安全版本,尽管它并未直接实现栈操作的方法,但是Deque的接口方法可以相对应地使用。
736 12
|
Java API 网络架构
java调用api接口自动判断节假日信息
java调用api接口自动判断节假日信息
4200 0
|
消息中间件 缓存 前端开发
从资损百万到零事故:Java 接口幂等设计的艺术与实践
在分布式系统中,重复请求常引发严重资损,如支付双扣、库存超卖等问题,其根源在于接口缺乏幂等性设计。本文通过真实案例揭示幂等性的重要性,并详解8种主流解决方案,涵盖唯一请求ID、乐观锁、悲观锁、状态机等,帮助开发者构建稳定系统,保障业务一致性。无论你是架构师还是开发工程师,都能从中获得实战指导,有效规避重复调用带来的风险。
1575 2
|
存储 安全 Java
深入理解Java序列化接口及其实现机制
记住,序列化不仅仅是把对象状态保存下来那么简单,它涉及到类的版本控制、安全性和性能等多个重要方面。正确理解和实现Java序列化机制对于构建高效、安全和可维护的Java应用至关重要。
465 0
|
安全 Java API
Java 抽象类与接口在 Java17 + 开发中的现代应用实践解析
《Java抽象类与接口核心技术解析》 摘要:本文全面剖析Java抽象类与接口的核心概念与技术差异。抽象类通过模板设计实现代码复用,支持具体方法与状态管理;接口则定义行为规范,实现多态支持。文章详细对比了两者在实例化、方法实现、继承机制等方面的区别,并提供了模板方法模式(抽象类)和策略模式(接口)的典型应用示例。特别指出Java8+新特性为接口带来的灵活性提升,包括默认方法和静态方法。最后给出最佳实践建议:优先使用接口定义行为规范,通过抽象类实现代码复用,合理组合两者构建灵活架构。
596 2