Java 调用Restful API接口的几种方式(HTTPS)

 更新时间:2018年02月11日 14:10:32   作者:三 丰  
这篇文章主要介绍了Java 调用Restful API接口的几种方式(HTTPS),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

摘要:最近有一个需求,为客户提供一些Restful API 接口,QA使用postman进行测试,但是postman的测试接口与java调用的相似但并不相同,于是想自己写一个程序去测试Restful API接口,由于使用的是HTTPS,所以还要考虑到对于HTTPS的处理。由于我也是首次使用Java调用restful接口,所以还要研究一番,自然也是查阅了一些资料。

分析:这个问题与模块之间的调用不同,比如我有两个模块front end 和back end,front end提供前台展示,back end提供数据支持。之前使用过Hession去把back end提供的服务注册成远程服务,在front end端可以通过这种远程服务直接调到back end的接口。但这对于一个公司自己的一个项目耦合性比较高的情况下使用,没有问题。但是如果给客户注册这种远程服务,似乎不太好,耦合性太高。所以就考虑用一下方式进行处理。

一、HttpClient

HttpClient大家也许比较熟悉但又比较陌生,熟悉是知道他可以远程调用比如请求一个URL,然后在response里获取到返回状态和返回信息,但是今天讲的稍微复杂一点,因为今天的主题是HTTPS,这个牵涉到证书或用户认证的问题。
确定使用HttpClient之后,查询相关资料,发现HttpClient的新版本与老版本不同,随然兼容老版本,但已经不提倡老版本是使用方式,很多都已经标记为过时的方法或类。今天就分别使用老版本4.2和最新版本4.5.3来写代码。

老版本4.2

需要认证

在准备证书阶段选择的是使用证书认证

package com.darren.test.https.v42; 
import java.io.File; 
import java.io.FileInputStream; 
import java.security.KeyStore; 
import org.apache.http.conn.ssl.SSLSocketFactory;  
public class HTTPSCertifiedClient extends HTTPSClient {  
  public HTTPSCertifiedClient() { 
 
  } 
 
  @Override 
  public void prepareCertificate() throws Exception { 
    // 获得密匙库 
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
    FileInputStream instream = new FileInputStream( 
        new File("C:/Users/zhda6001/Downloads/software/xxx.keystore")); 
    // FileInputStream instream = new FileInputStream(new File("C:/Users/zhda6001/Downloads/xxx.keystore")); 
    // 密匙库的密码 
    trustStore.load(instream, "password".toCharArray()); 
    // 注册密匙库 
    this.socketFactory = new SSLSocketFactory(trustStore); 
    // 不校验域名 
    socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 
  } 
} 

跳过认证

在准备证书阶段选择的是跳过认证

package com.darren.test.https.v42;  
import java.security.cert.CertificateException; 
import java.security.cert.X509Certificate; 
import javax.net.ssl.SSLContext; 
import javax.net.ssl.TrustManager; 
import javax.net.ssl.X509TrustManager;  
import org.apache.http.conn.ssl.SSLSocketFactory; 
public class HTTPSTrustClient extends HTTPSClient { 
  public HTTPSTrustClient() { 
 
  } 
 
  @Override 
  public void prepareCertificate() throws Exception { 
    // 跳过证书验证 
    SSLContext ctx = SSLContext.getInstance("TLS"); 
    X509TrustManager tm = new X509TrustManager() { 
      @Override 
      public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 
      } 
 
      @Override 
      public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 
      } 
 
      @Override 
      public X509Certificate[] getAcceptedIssuers() { 
        return null; 
      } 
    }; 
    // 设置成已信任的证书 
    ctx.init(null, new TrustManager[] { tm }, null); 
    // 穿件SSL socket 工厂,并且设置不检查host名称 
    this.socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 
  } 
} 

总结

现在发现这两个类都继承了同一个类HTTPSClient,并且HTTPSClient继承了DefaultHttpClient类,可以发现,这里使用了模板方法模式。

package com.darren.test.https.v42; 
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.impl.client.DefaultHttpClient;  
public abstract class HTTPSClient extends DefaultHttpClient {  
  protected SSLSocketFactory socketFactory; 
 
  /** 
   * 初始化HTTPSClient 
   * 
   * @return 返回当前实例 
   * @throws Exception 
   */ 
  public HTTPSClient init() throws Exception { 
    this.prepareCertificate(); 
    this.regist(); 
 
    return this; 
  }  
  /** 
   * 准备证书验证 
   * 
   * @throws Exception 
   */ 
  public abstract void prepareCertificate() throws Exception; 
 
  /** 
   * 注册协议和端口, 此方法也可以被子类重写 
   */ 
  protected void regist() { 
    ClientConnectionManager ccm = this.getConnectionManager(); 
    SchemeRegistry sr = ccm.getSchemeRegistry(); 
    sr.register(new Scheme("https", 443, socketFactory)); 
  } 
} 

下边是工具类

package com.darren.test.https.v42;  
import java.util.ArrayList; 
import java.util.List; 
import java.util.Map; 
import java.util.Set; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.methods.HttpRequestBase; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.util.EntityUtils;  
public class HTTPSClientUtil { 
  private static final String DEFAULT_CHARSET = "UTF-8";  
  public static String doPost(HTTPSClient httpsClient, String url, Map<String, String> paramHeader, 
      Map<String, String> paramBody) throws Exception { 
    return doPost(httpsClient, url, paramHeader, paramBody, DEFAULT_CHARSET); 
  } 
 
  public static String doPost(HTTPSClient httpsClient, String url, Map<String, String> paramHeader, 
      Map<String, String> paramBody, String charset) throws Exception { 
 
    String result = null; 
    HttpPost httpPost = new HttpPost(url); 
    setHeader(httpPost, paramHeader); 
    setBody(httpPost, paramBody, charset); 
 
    HttpResponse response = httpsClient.execute(httpPost); 
    if (response != null) { 
      HttpEntity resEntity = response.getEntity(); 
      if (resEntity != null) { 
        result = EntityUtils.toString(resEntity, charset); 
      } 
    } 
 
    return result; 
  } 
   
  public static String doGet(HTTPSClient httpsClient, String url, Map<String, String> paramHeader, 
      Map<String, String> paramBody) throws Exception { 
    return doGet(httpsClient, url, paramHeader, paramBody, DEFAULT_CHARSET); 
  } 
 
  public static String doGet(HTTPSClient httpsClient, String url, Map<String, String> paramHeader, 
      Map<String, String> paramBody, String charset) throws Exception { 
 
    String result = null; 
    HttpGet httpGet = new HttpGet(url); 
    setHeader(httpGet, paramHeader); 
 
    HttpResponse response = httpsClient.execute(httpGet); 
    if (response != null) { 
      HttpEntity resEntity = response.getEntity(); 
      if (resEntity != null) { 
        result = EntityUtils.toString(resEntity, charset); 
      } 
    } 
 
    return result; 
  } 
 
  private static void setHeader(HttpRequestBase request, Map<String, String> paramHeader) { 
    // 设置Header 
    if (paramHeader != null) { 
      Set<String> keySet = paramHeader.keySet(); 
      for (String key : keySet) { 
        request.addHeader(key, paramHeader.get(key)); 
      } 
    } 
  } 
 
  private static void setBody(HttpPost httpPost, Map<String, String> paramBody, String charset) throws Exception { 
    // 设置参数 
    if (paramBody != null) { 
      List<NameValuePair> list = new ArrayList<NameValuePair>(); 
      Set<String> keySet = paramBody.keySet(); 
      for (String key : keySet) { 
        list.add(new BasicNameValuePair(key, paramBody.get(key))); 
      } 
 
      if (list.size() > 0) { 
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset); 
        httpPost.setEntity(entity); 
      } 
    } 
  } 
} 

然后是测试类:

package com.darren.test.https.v42; 
import java.util.HashMap; 
import java.util.Map;  
public class HTTPSClientTest {  
  public static void main(String[] args) throws Exception { 
    HTTPSClient httpsClient = null; 
 
    httpsClient = new HTTPSTrustClient().init(); 
    //httpsClient = new HTTPSCertifiedClient().init(); 
 
    String url = "https://1.2.6.2:8011/xxx/api/getToken"; 
    //String url = "https://1.2.6.2:8011/xxx/api/getHealth"; 
 
    Map<String, String> paramHeader = new HashMap<>(); 
    //paramHeader.put("Content-Type", "application/json"); 
    paramHeader.put("Accept", "application/xml"); 
    Map<String, String> paramBody = new HashMap<>(); 
    paramBody.put("client_id", "ankur.tandon.ap@xxx.com"); 
    paramBody.put("client_secret", "P@ssword_1"); 
    String result = HTTPSClientUtil.doPost(httpsClient, url, paramHeader, paramBody); 
     
    //String result = HTTPSClientUtil.doGet(httpsClient, url, null, null); 
     
    System.out.println(result); 
  }  
} 

返回信息:

<?xml version="1.0" encoding="utf-8"?>   
<token>jkf8RL0sw+Skkflj8RbKI5hP1bEQK8PrCuTZPpBINqMYKRMxY1kWCjmCfT191Zpp88VV1aGHW8oYNWjEYS0axpLuGAX89ejCoWNbikCc1UvfyesXHLktcJqyUFiVjevhrEQxJPHncLQYWP+Xse5oD9X8vKFKk7InNTMRzQK7YBTZ/e3U7gswM/5cvAHFl6o9rEq9cWPXavZNohyvnXsohSzDo+BXAtXxa1xpEDLy/8h/UaP4n4dlZDJJ3B8t1Xh+CRRIoMOPxf7c5wKhHtOkEOeXW+xoPQKKSx5CKWwJpPuGIIFWF/PaqWg+JUOsVT7QGdPv8PMWJ9DwEwjTdxguDg==</token> 

新版本4.5.3

需要认证

package com.darren.test.https.v45;  
import java.io.File; 
import java.io.FileInputStream; 
import java.security.KeyStore; 
import javax.net.ssl.SSLContext; 
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 
import org.apache.http.conn.ssl.TrustSelfSignedStrategy; 
import org.apache.http.ssl.SSLContexts;  
public class HTTPSCertifiedClient extends HTTPSClient {  
  public HTTPSCertifiedClient() { 
 
  } 
 
  @Override 
  public void prepareCertificate() throws Exception { 
    // 获得密匙库 
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
    FileInputStream instream = new FileInputStream( 
        new File("C:/Users/zhda6001/Downloads/software/xxx.keystore")); 
    // FileInputStream instream = new FileInputStream(new File("C:/Users/zhda6001/Downloads/xxx.keystore")); 
    try { 
      // 密匙库的密码 
      trustStore.load(instream, "password".toCharArray()); 
    } finally { 
      instream.close(); 
    }  
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, TrustSelfSignedStrategy.INSTANCE) 
        .build(); 
    this.connectionSocketFactory = new SSLConnectionSocketFactory(sslcontext); 
  }  
} 

跳过认证

package com.darren.test.https.v45;  
import java.security.cert.CertificateException; 
import java.security.cert.X509Certificate; 
import javax.net.ssl.SSLContext; 
import javax.net.ssl.TrustManager; 
import javax.net.ssl.X509TrustManager; 
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 
public class HTTPSTrustClient extends HTTPSClient { 
  public HTTPSTrustClient() {  
  } 
 
  @Override 
  public void prepareCertificate() throws Exception { 
    // 跳过证书验证 
    SSLContext ctx = SSLContext.getInstance("TLS"); 
    X509TrustManager tm = new X509TrustManager() { 
      @Override 
      public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 
      } 
 
      @Override 
      public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 
      } 
 
      @Override 
      public X509Certificate[] getAcceptedIssuers() { 
        return null; 
      } 
    }; 
    // 设置成已信任的证书 
    ctx.init(null, new TrustManager[] { tm }, null); 
    this.connectionSocketFactory = new SSLConnectionSocketFactory(ctx); 
  } 
} 

总结

package com.darren.test.https.v45;  
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.impl.client.CloseableHttpClient; 
import org.apache.http.impl.client.HttpClientBuilder; 
import org.apache.http.impl.client.HttpClients; 
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;  
public abstract class HTTPSClient extends HttpClientBuilder { 
  private CloseableHttpClient client; 
  protected ConnectionSocketFactory connectionSocketFactory; 
 
  /** 
   * 初始化HTTPSClient 
   * 
   * @return 返回当前实例 
   * @throws Exception 
   */ 
  public CloseableHttpClient init() throws Exception { 
    this.prepareCertificate(); 
    this.regist(); 
 
    return this.client; 
  } 
 
  /** 
   * 准备证书验证 
   * 
   * @throws Exception 
   */ 
  public abstract void prepareCertificate() throws Exception; 
 
  /** 
   * 注册协议和端口, 此方法也可以被子类重写 
   */ 
  protected void regist() { 
    // 设置协议http和https对应的处理socket链接工厂的对象 
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() 
        .register("http", PlainConnectionSocketFactory.INSTANCE) 
        .register("https", this.connectionSocketFactory) 
        .build(); 
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); 
    HttpClients.custom().setConnectionManager(connManager); 
 
    // 创建自定义的httpclient对象 
    this.client = HttpClients.custom().setConnectionManager(connManager).build(); 
    // CloseableHttpClient client = HttpClients.createDefault(); 
  } 
} 

工具类:

package com.darren.test.https.v45;  
import java.util.ArrayList; 
import java.util.List; 
import java.util.Map; 
import java.util.Set;  
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.methods.HttpRequestBase; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.util.EntityUtils;  
public class HTTPSClientUtil { 
  private static final String DEFAULT_CHARSET = "UTF-8";  
  public static String doPost(HttpClient httpClient, String url, Map<String, String> paramHeader, 
      Map<String, String> paramBody) throws Exception { 
    return doPost(httpClient, url, paramHeader, paramBody, DEFAULT_CHARSET); 
  } 
 
  public static String doPost(HttpClient httpClient, String url, Map<String, String> paramHeader, 
      Map<String, String> paramBody, String charset) throws Exception { 
 
    String result = null; 
    HttpPost httpPost = new HttpPost(url); 
    setHeader(httpPost, paramHeader); 
    setBody(httpPost, paramBody, charset);  
    HttpResponse response = httpClient.execute(httpPost); 
    if (response != null) { 
      HttpEntity resEntity = response.getEntity(); 
      if (resEntity != null) { 
        result = EntityUtils.toString(resEntity, charset); 
      } 
    } 
 
    return result; 
  } 
   
  public static String doGet(HttpClient httpClient, String url, Map<String, String> paramHeader, 
      Map<String, String> paramBody) throws Exception { 
    return doGet(httpClient, url, paramHeader, paramBody, DEFAULT_CHARSET); 
  } 
 
  public static String doGet(HttpClient httpClient, String url, Map<String, String> paramHeader, 
      Map<String, String> paramBody, String charset) throws Exception { 
 
    String result = null; 
    HttpGet httpGet = new HttpGet(url); 
    setHeader(httpGet, paramHeader); 
 
    HttpResponse response = httpClient.execute(httpGet); 
    if (response != null) { 
      HttpEntity resEntity = response.getEntity(); 
      if (resEntity != null) { 
        result = EntityUtils.toString(resEntity, charset); 
      } 
    } 
 
    return result; 
  } 
 
  private static void setHeader(HttpRequestBase request, Map<String, String> paramHeader) { 
    // 设置Header 
    if (paramHeader != null) { 
      Set<String> keySet = paramHeader.keySet(); 
      for (String key : keySet) { 
        request.addHeader(key, paramHeader.get(key)); 
      } 
    } 
  } 
 
  private static void setBody(HttpPost httpPost, Map<String, String> paramBody, String charset) throws Exception { 
    // 设置参数 
    if (paramBody != null) { 
      List<NameValuePair> list = new ArrayList<NameValuePair>(); 
      Set<String> keySet = paramBody.keySet(); 
      for (String key : keySet) { 
        list.add(new BasicNameValuePair(key, paramBody.get(key))); 
      } 
 
      if (list.size() > 0) { 
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset); 
        httpPost.setEntity(entity); 
      } 
    } 
  } 
} 

测试类:

package com.darren.test.https.v45;  
import java.util.HashMap; 
import java.util.Map; 
import org.apache.http.client.HttpClient;  
public class HTTPSClientTest {  
  public static void main(String[] args) throws Exception { 
    HttpClient httpClient = null; 
 
    //httpClient = new HTTPSTrustClient().init(); 
    httpClient = new HTTPSCertifiedClient().init(); 
 
    String url = "https://1.2.6.2:8011/xxx/api/getToken"; 
    //String url = "https://1.2.6.2:8011/xxx/api/getHealth"; 
 
    Map<String, String> paramHeader = new HashMap<>(); 
    paramHeader.put("Accept", "application/xml"); 
    Map<String, String> paramBody = new HashMap<>(); 
    paramBody.put("client_id", "ankur.tandon.ap@xxx.com"); 
    paramBody.put("client_secret", "P@ssword_1"); 
    String result = HTTPSClientUtil.doPost(httpClient, url, paramHeader, paramBody); 
     
    //String result = HTTPSClientUtil.doGet(httpsClient, url, null, null); 
     
    System.out.println(result); 
  } 
 
} 

结果:

<?xml version="1.0" encoding="utf-8"?>   
<token>RxitF9//7NxwXJS2cjIjYhLtvzUNvMZxxEQtGN0u07sC9ysJeIbPqte3hCjULSkoXPEUYGUVeyI9jv7/WikLrzxYKc3OSpaTSM0kCbCKphu0TB2Cn/nfzv9fMLueOWFBdyz+N0sEiI9K+0Gp7920DFEncn17wUJVmC0u2jwvM5FAjQKmilwodXZ6a0Dq+D7dQDJwVcwxBvJ2ilhyIb3pr805Vppmi9atXrVAKO0ODa006wEJFOfcgyG5p70wpJ5rrBL85vfy9WCvkd1R7j6NVjhXgH2gNimHkjEJorMjdXW2gKiUsiWsELi/XPswao7/CTWNwTnctGK8PX2ZUB0ZfA==</token> 

二、HttpURLConnection

三、Spring的RestTemplate

其它方式以后补充

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Java设计模式之java观察者模式详解

    Java设计模式之java观察者模式详解

    这篇文章主要介绍了Java经典设计模式之观察者模式,简单分析了观察者模式的概念、原理并结合实例形式给出了java观察者模式的具体用法与相关注意事项,需要的朋友可以参考下
    2021-09-09
  • Java基于享元模式实现五子棋游戏功能实例详解

    Java基于享元模式实现五子棋游戏功能实例详解

    这篇文章主要介绍了Java基于享元模式实现五子棋游戏功能,较为详细的分析了享元模式的概念、功能并结合实例形式详细分析了Java使用享元模式实现五子棋游戏的具体操作步骤与相关注意事项,需要的朋友可以参考下
    2018-05-05
  • java枚举是如何保证线程安全的

    java枚举是如何保证线程安全的

    这篇文章主要介绍了java枚举是如何保证线程安全的。Java SE5提供了一种新的类型-Java的枚举类型,关键字enum可以将一组具名的值的有限集合创建为一种新的类型,而这些具名的值可以作为常规的程序组件使用,这是一种非常有用的功能。,需要的朋友可以参考下
    2019-06-06
  • SpringCloud Feign传递HttpServletRequest对象流程

    SpringCloud Feign传递HttpServletRequest对象流程

    HttpServletRequest接口的对象代表客户端的请求,当客户端通过HTTP协议访问Tomcat服务器时,HTTP请求中的所有信息都封装在HttpServletRequest接口的对象中,这篇文章介绍了Feign传递HttpServletRequest对象的流程,感兴趣的同学可以参考下文
    2023-05-05
  • 2020新版idea创建项目没有javaEE 没有Web选项的完美解决方法

    2020新版idea创建项目没有javaEE 没有Web选项的完美解决方法

    这篇文章主要介绍了2020新版idea创建项目没有javaEE 没有Web选项的完美解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-09-09
  • Java之SpringBoot自定义配置与整合Druid

    Java之SpringBoot自定义配置与整合Druid

    这篇文章主要介绍的是java之SpringBoot自定义配置与整合Druid的相关资料,关于SpringBoot配置文件可以是properties或者是yaml格式的文件,但是在SpringBoot加载application配置文件时是存在一个优先级,下面小编就和大家一起进入文章学习这项知识
    2021-09-09
  • java经典问题:连个字符串互为回环变位

    java经典问题:连个字符串互为回环变位

    连个字符串互为回环变位经常出现在java程序员面试中,这个是考验程序员的解题思路和方法的最经典的一题,小编为大家详细分析一下,一起来学习吧。
    2017-11-11
  • java calendar 日期实现不断加一天的代码

    java calendar 日期实现不断加一天的代码

    这篇文章主要介绍了java calendar 日期实现不断加一天的代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-10-10
  • 浅析Java内存模型与垃圾回收

    浅析Java内存模型与垃圾回收

    下面小编就为大家带来一篇浅析Java内存模型与垃圾回收。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧,祝大家游戏愉快哦
    2016-05-05
  • Java 十大排序算法之选择排序刨析

    Java 十大排序算法之选择排序刨析

    选择排序是一种简单直观的排序算法,无论什么数据进去都是 O(n&sup2;) 的时间复杂度。所以用到它的时候,数据规模越小越好。唯一的好处可能就是不占用额外的内存空间了吧
    2021-11-11

最新评论