Java调用Restful API接口几种方式

 

2018年01月16日 22:18:40 Exceed Oneself 阅读数:1968

摘要:最近有一个需求,为客户提供一些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

需要认证


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

[java] view plain copy

  1. package com.darren.test.https.v42;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.security.KeyStore;  
  6.   
  7. import org.apache.http.conn.ssl.SSLSocketFactory;  
  8.   
  9. public class HTTPSCertifiedClient extends HTTPSClient {  
  10.   
  11.     public HTTPSCertifiedClient() {  
  12.   
  13.     }  
  14.   
  15.     @Override  
  16.     public void prepareCertificate() throws Exception {  
  17.         // 获得密匙库  
  18.         KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
  19.         FileInputStream instream = new FileInputStream(  
  20.                 new File("C:/Users/zhda6001/Downloads/software/xxx.keystore"));  
  21.         // FileInputStream instream = new FileInputStream(new File("C:/Users/zhda6001/Downloads/xxx.keystore"));  
  22.         // 密匙库的密码  
  23.         trustStore.load(instream, "password".toCharArray());  
  24.         // 注册密匙库  
  25.         this.socketFactory = new SSLSocketFactory(trustStore);  
  26.         // 不校验域名  
  27.         socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  28.     }  
  29. }  

跳过认证

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

[java] view plain copy

  1. package com.darren.test.https.v42;  
  2.   
  3. import java.security.cert.CertificateException;  
  4. import java.security.cert.X509Certificate;  
  5.   
  6. import javax.net.ssl.SSLContext;  
  7. import javax.net.ssl.TrustManager;  
  8. import javax.net.ssl.X509TrustManager;  
  9.   
  10. import org.apache.http.conn.ssl.SSLSocketFactory;  
  11.   
  12. public class HTTPSTrustClient extends HTTPSClient {  
  13.   
  14.     public HTTPSTrustClient() {  
  15.   
  16.     }  
  17.   
  18.     @Override  
  19.     public void prepareCertificate() throws Exception {  
  20.         // 跳过证书验证  
  21.         SSLContext ctx = SSLContext.getInstance("TLS");  
  22.         X509TrustManager tm = new X509TrustManager() {  
  23.             @Override  
  24.             public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
  25.             }  
  26.   
  27.             @Override  
  28.             public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
  29.             }  
  30.   
  31.             @Override  
  32.             public X509Certificate[] getAcceptedIssuers() {  
  33.                 return null;  
  34.             }  
  35.         };  
  36.         // 设置成已信任的证书  
  37.         ctx.init(null, new TrustManager[] { tm }, null);  
  38.         // 穿件SSL socket 工厂,并且设置不检查host名称  
  39.         this.socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  40.     }  
  41. }  

总结

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

[java] view plain copy

  1. package com.darren.test.https.v42;  
  2.   
  3. import org.apache.http.conn.ClientConnectionManager;  
  4. import org.apache.http.conn.scheme.Scheme;  
  5. import org.apache.http.conn.scheme.SchemeRegistry;  
  6. import org.apache.http.conn.ssl.SSLSocketFactory;  
  7. import org.apache.http.impl.client.DefaultHttpClient;  
  8.   
  9. public abstract class HTTPSClient extends DefaultHttpClient {  
  10.   
  11.     protected SSLSocketFactory socketFactory;  
  12.   
  13.     /** 
  14.      * 初始化HTTPSClient 
  15.      *  
  16.      * @return 返回当前实例 
  17.      * @throws Exception 
  18.      */  
  19.     public HTTPSClient init() throws Exception {  
  20.         this.prepareCertificate();  
  21.         this.regist();  
  22.   
  23.         return this;  
  24.     }  
  25.   
  26.     /** 
  27.      * 准备证书验证 
  28.      *  
  29.      * @throws Exception 
  30.      */  
  31.     public abstract void prepareCertificate() throws Exception;  
  32.   
  33.     /** 
  34.      * 注册协议和端口, 此方法也可以被子类重写 
  35.      */  
  36.     protected void regist() {  
  37.         ClientConnectionManager ccm = this.getConnectionManager();  
  38.         SchemeRegistry sr = ccm.getSchemeRegistry();  
  39.         sr.register(new Scheme("https", 443, socketFactory));  
  40.     }  
  41. }  


下边是工具类

[java] view plain copy

  1. package com.darren.test.https.v42;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import java.util.Set;  
  7.   
  8. import org.apache.http.HttpEntity;  
  9. import org.apache.http.HttpResponse;  
  10. import org.apache.http.NameValuePair;  
  11. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  12. import org.apache.http.client.methods.HttpGet;  
  13. import org.apache.http.client.methods.HttpPost;  
  14. import org.apache.http.client.methods.HttpRequestBase;  
  15. import org.apache.http.message.BasicNameValuePair;  
  16. import org.apache.http.util.EntityUtils;  
  17.   
  18. public class HTTPSClientUtil {  
  19.     private static final String DEFAULT_CHARSET = "UTF-8";  
  20.   
  21.     public static String doPost(HTTPSClient httpsClient, String url, Map<String, String> paramHeader,  
  22.             Map<String, String> paramBody) throws Exception {  
  23.         return doPost(httpsClient, url, paramHeader, paramBody, DEFAULT_CHARSET);  
  24.     }  
  25.   
  26.     public static String doPost(HTTPSClient httpsClient, String url, Map<String, String> paramHeader,  
  27.             Map<String, String> paramBody, String charset) throws Exception {  
  28.   
  29.         String result = null;  
  30.         HttpPost httpPost = new HttpPost(url);  
  31.         setHeader(httpPost, paramHeader);  
  32.         setBody(httpPost, paramBody, charset);  
  33.   
  34.         HttpResponse response = httpsClient.execute(httpPost);  
  35.         if (response != null) {  
  36.             HttpEntity resEntity = response.getEntity();  
  37.             if (resEntity != null) {  
  38.                 result = EntityUtils.toString(resEntity, charset);  
  39.             }  
  40.         }  
  41.   
  42.         return result;  
  43.     }  
  44.       
  45.     public static String doGet(HTTPSClient httpsClient, String url, Map<String, String> paramHeader,  
  46.             Map<String, String> paramBody) throws Exception {  
  47.         return doGet(httpsClient, url, paramHeader, paramBody, DEFAULT_CHARSET);  
  48.     }  
  49.   
  50.     public static String doGet(HTTPSClient httpsClient, String url, Map<String, String> paramHeader,  
  51.             Map<String, String> paramBody, String charset) throws Exception {  
  52.   
  53.         String result = null;  
  54.         HttpGet httpGet = new HttpGet(url);  
  55.         setHeader(httpGet, paramHeader);  
  56.   
  57.         HttpResponse response = httpsClient.execute(httpGet);  
  58.         if (response != null) {  
  59.             HttpEntity resEntity = response.getEntity();  
  60.             if (resEntity != null) {  
  61.                 result = EntityUtils.toString(resEntity, charset);  
  62.             }  
  63.         }  
  64.   
  65.         return result;  
  66.     }  
  67.   
  68.     private static void setHeader(HttpRequestBase request, Map<String, String> paramHeader) {  
  69.         // 设置Header  
  70.         if (paramHeader != null) {  
  71.             Set<String> keySet = paramHeader.keySet();  
  72.             for (String key : keySet) {  
  73.                 request.addHeader(key, paramHeader.get(key));  
  74.             }  
  75.         }  
  76.     }  
  77.   
  78.     private static void setBody(HttpPost httpPost, Map<String, String> paramBody, String charset) throws Exception {  
  79.         // 设置参数  
  80.         if (paramBody != null) {  
  81.             List<NameValuePair> list = new ArrayList<NameValuePair>();  
  82.             Set<String> keySet = paramBody.keySet();  
  83.             for (String key : keySet) {  
  84.                 list.add(new BasicNameValuePair(key, paramBody.get(key)));  
  85.             }  
  86.   
  87.             if (list.size() > 0) {  
  88.                 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);  
  89.                 httpPost.setEntity(entity);  
  90.             }  
  91.         }  
  92.     }  
  93. }  


然后是测试类:

[java] view plain copy

  1. package com.darren.test.https.v42;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. public class HTTPSClientTest {  
  7.   
  8.     public static void main(String[] args) throws Exception {  
  9.         HTTPSClient httpsClient = null;  
  10.   
  11.         httpsClient = new HTTPSTrustClient().init();  
  12.         //httpsClient = new HTTPSCertifiedClient().init();  
  13.   
  14.         String url = "https://1.2.6.2:8011/xxx/api/getToken";  
  15.         //String url = "https://1.2.6.2:8011/xxx/api/getHealth";  
  16.   
  17.         Map<String, String> paramHeader = new HashMap<>();  
  18.         //paramHeader.put("Content-Type", "application/json");  
  19.         paramHeader.put("Accept", "application/xml");  
  20.         Map<String, String> paramBody = new HashMap<>();  
  21.         paramBody.put("client_id", "[email protected]");  
  22.         paramBody.put("client_secret", "P@ssword_1");  
  23.         String result = HTTPSClientUtil.doPost(httpsClient, url, paramHeader, paramBody);  
  24.           
  25.         //String result = HTTPSClientUtil.doGet(httpsClient, url, null, null);  
  26.           
  27.         System.out.println(result);  
  28.     }  
  29.   
  30. }  


返回信息:

[html] view plain copy

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

新版本4.5.3

需要认证

[java] view plain copy

  1. package com.darren.test.https.v45;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.security.KeyStore;  
  6.   
  7. import javax.net.ssl.SSLContext;  
  8.   
  9. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  10. import org.apache.http.conn.ssl.TrustSelfSignedStrategy;  
  11. import org.apache.http.ssl.SSLContexts;  
  12.   
  13. public class HTTPSCertifiedClient extends HTTPSClient {  
  14.   
  15.     public HTTPSCertifiedClient() {  
  16.   
  17.     }  
  18.   
  19.     @Override  
  20.     public void prepareCertificate() throws Exception {  
  21.         // 获得密匙库  
  22.         KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
  23.         FileInputStream instream = new FileInputStream(  
  24.                 new File("C:/Users/zhda6001/Downloads/software/xxx.keystore"));  
  25.         // FileInputStream instream = new FileInputStream(new File("C:/Users/zhda6001/Downloads/xxx.keystore"));  
  26.         try {  
  27.             // 密匙库的密码  
  28.             trustStore.load(instream, "password".toCharArray());  
  29.         } finally {  
  30.             instream.close();  
  31.         }  
  32.   
  33.         SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, TrustSelfSignedStrategy.INSTANCE)  
  34.                 .build();  
  35.         this.connectionSocketFactory = new SSLConnectionSocketFactory(sslcontext);  
  36.     }  
  37.   
  38. }  

跳过认证

[java] view plain copy

  1. package com.darren.test.https.v45;  
  2.   
  3. import java.security.cert.CertificateException;  
  4. import java.security.cert.X509Certificate;  
  5.   
  6. import javax.net.ssl.SSLContext;  
  7. import javax.net.ssl.TrustManager;  
  8. import javax.net.ssl.X509TrustManager;  
  9.   
  10. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  11.   
  12. public class HTTPSTrustClient extends HTTPSClient {  
  13.   
  14.     public HTTPSTrustClient() {  
  15.   
  16.     }  
  17.   
  18.     @Override  
  19.     public void prepareCertificate() throws Exception {  
  20.         // 跳过证书验证  
  21.         SSLContext ctx = SSLContext.getInstance("TLS");  
  22.         X509TrustManager tm = new X509TrustManager() {  
  23.             @Override  
  24.             public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
  25.             }  
  26.   
  27.             @Override  
  28.             public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
  29.             }  
  30.   
  31.             @Override  
  32.             public X509Certificate[] getAcceptedIssuers() {  
  33.                 return null;  
  34.             }  
  35.         };  
  36.         // 设置成已信任的证书  
  37.         ctx.init(null, new TrustManager[] { tm }, null);  
  38.         this.connectionSocketFactory = new SSLConnectionSocketFactory(ctx);  
  39.     }  
  40. }  

总结

[java] view plain copy

  1. package com.darren.test.https.v45;  
  2.   
  3. import org.apache.http.config.Registry;  
  4. import org.apache.http.config.RegistryBuilder;  
  5. import org.apache.http.conn.socket.ConnectionSocketFactory;  
  6. import org.apache.http.conn.socket.PlainConnectionSocketFactory;  
  7. import org.apache.http.impl.client.CloseableHttpClient;  
  8. import org.apache.http.impl.client.HttpClientBuilder;  
  9. import org.apache.http.impl.client.HttpClients;  
  10. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;  
  11.   
  12. public abstract class HTTPSClient extends HttpClientBuilder {  
  13.     private CloseableHttpClient client;  
  14.     protected ConnectionSocketFactory connectionSocketFactory;  
  15.   
  16.     /** 
  17.      * 初始化HTTPSClient 
  18.      *  
  19.      * @return 返回当前实例 
  20.      * @throws Exception 
  21.      */  
  22.     public CloseableHttpClient init() throws Exception {  
  23.         this.prepareCertificate();  
  24.         this.regist();  
  25.   
  26.         return this.client;  
  27.     }  
  28.   
  29.     /** 
  30.      * 准备证书验证 
  31.      *  
  32.      * @throws Exception 
  33.      */  
  34.     public abstract void prepareCertificate() throws Exception;  
  35.   
  36.     /** 
  37.      * 注册协议和端口, 此方法也可以被子类重写 
  38.      */  
  39.     protected void regist() {  
  40.         // 设置协议http和https对应的处理socket链接工厂的对象  
  41.         Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()  
  42.                 .register("http", PlainConnectionSocketFactory.INSTANCE)  
  43.                 .register("https", this.connectionSocketFactory)  
  44.                 .build();  
  45.         PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);  
  46.         HttpClients.custom().setConnectionManager(connManager);  
  47.   
  48.         // 创建自定义的httpclient对象  
  49.         this.client = HttpClients.custom().setConnectionManager(connManager).build();  
  50.         // CloseableHttpClient client = HttpClients.createDefault();  
  51.     }  
  52. }  

工具类:

[java] view plain copy

  1. package com.darren.test.https.v45;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import java.util.Set;  
  7.   
  8. import org.apache.http.HttpEntity;  
  9. import org.apache.http.HttpResponse;  
  10. import org.apache.http.NameValuePair;  
  11. import org.apache.http.client.HttpClient;  
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  13. import org.apache.http.client.methods.HttpGet;  
  14. import org.apache.http.client.methods.HttpPost;  
  15. import org.apache.http.client.methods.HttpRequestBase;  
  16. import org.apache.http.message.BasicNameValuePair;  
  17. import org.apache.http.util.EntityUtils;  
  18.   
  19. public class HTTPSClientUtil {  
  20.     private static final String DEFAULT_CHARSET = "UTF-8";  
  21.   
  22.     public static String doPost(HttpClient httpClient, String url, Map<String, String> paramHeader,  
  23.             Map<String, String> paramBody) throws Exception {  
  24.         return doPost(httpClient, url, paramHeader, paramBody, DEFAULT_CHARSET);  
  25.     }  
  26.   
  27.     public static String doPost(HttpClient httpClient, String url, Map<String, String> paramHeader,  
  28.             Map<String, String> paramBody, String charset) throws Exception {  
  29.   
  30.         String result = null;  
  31.         HttpPost httpPost = new HttpPost(url);  
  32.         setHeader(httpPost, paramHeader);  
  33.         setBody(httpPost, paramBody, charset);  
  34.   
  35.         HttpResponse response = httpClient.execute(httpPost);  
  36.         if (response != null) {  
  37.             HttpEntity resEntity = response.getEntity();  
  38.             if (resEntity != null) {  
  39.                 result = EntityUtils.toString(resEntity, charset);  
  40.             }  
  41.         }  
  42.   
  43.         return result;  
  44.     }  
  45.       
  46.     public static String doGet(HttpClient httpClient, String url, Map<String, String> paramHeader,  
  47.             Map<String, String> paramBody) throws Exception {  
  48.         return doGet(httpClient, url, paramHeader, paramBody, DEFAULT_CHARSET);  
  49.     }  
  50.   
  51.     public static String doGet(HttpClient httpClient, String url, Map<String, String> paramHeader,  
  52.             Map<String, String> paramBody, String charset) throws Exception {  
  53.   
  54.         String result = null;  
  55.         HttpGet httpGet = new HttpGet(url);  
  56.         setHeader(httpGet, paramHeader);  
  57.   
  58.         HttpResponse response = httpClient.execute(httpGet);  
  59.         if (response != null) {  
  60.             HttpEntity resEntity = response.getEntity();  
  61.             if (resEntity != null) {  
  62.                 result = EntityUtils.toString(resEntity, charset);  
  63.             }  
  64.         }  
  65.   
  66.         return result;  
  67.     }  
  68.   
  69.     private static void setHeader(HttpRequestBase request, Map<String, String> paramHeader) {  
  70.         // 设置Header  
  71.         if (paramHeader != null) {  
  72.             Set<String> keySet = paramHeader.keySet();  
  73.             for (String key : keySet) {  
  74.                 request.addHeader(key, paramHeader.get(key));  
  75.             }  
  76.         }  
  77.     }  
  78.   
  79.     private static void setBody(HttpPost httpPost, Map<String, String> paramBody, String charset) throws Exception {  
  80.         // 设置参数  
  81.         if (paramBody != null) {  
  82.             List<NameValuePair> list = new ArrayList<NameValuePair>();  
  83.             Set<String> keySet = paramBody.keySet();  
  84.             for (String key : keySet) {  
  85.                 list.add(new BasicNameValuePair(key, paramBody.get(key)));  
  86.             }  
  87.   
  88.             if (list.size() > 0) {  
  89.                 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);  
  90.                 httpPost.setEntity(entity);  
  91.             }  
  92.         }  
  93.     }  
  94. }  

测试类:

[java] view plain copy

  1. package com.darren.test.https.v45;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import org.apache.http.client.HttpClient;  
  7.   
  8. public class HTTPSClientTest {  
  9.   
  10.     public static void main(String[] args) throws Exception {  
  11.         HttpClient httpClient = null;  
  12.   
  13.         //httpClient = new HTTPSTrustClient().init();  
  14.         httpClient = new HTTPSCertifiedClient().init();  
  15.   
  16.         String url = "https://1.2.6.2:8011/xxx/api/getToken";  
  17.         //String url = "https://1.2.6.2:8011/xxx/api/getHealth";  
  18.   
  19.         Map<String, String> paramHeader = new HashMap<>();  
  20.         paramHeader.put("Accept", "application/xml");  
  21.         Map<String, String> paramBody = new HashMap<>();  
  22.         paramBody.put("client_id", "[email protected]");  
  23.         paramBody.put("client_secret", "P@ssword_1");  
  24.         String result = HTTPSClientUtil.doPost(httpClient, url, paramHeader, paramBody);  
  25.           
  26.         //String result = HTTPSClientUtil.doGet(httpsClient, url, null, null);  
  27.           
  28.         System.out.println(result);  
  29.     }  
  30.   
  31. }  


结果:

[html] view plain copy

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


 

二、HttpURLConnection

三、Spring的RestTemplate

其它方式以后补充

参考:

JAVA利用HttpClient进行POST请求(HTTPS)

CloseableHttpClient加载证书来访问https网站

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

猜你喜欢

转载自blog.csdn.net/wangshuminjava/article/details/85879217