Java 調(diào)用Restful API接口的幾種方式(HTTPS)
摘要:最近有一個(gè)需求,為客戶(hù)提供一些Restful API 接口,QA使用postman進(jìn)行測(cè)試,但是postman的測(cè)試接口與java調(diào)用的相似但并不相同,于是想自己寫(xiě)一個(gè)程序去測(cè)試Restful API接口,由于使用的是HTTPS,所以還要考慮到對(duì)于HTTPS的處理。由于我也是首次使用Java調(diào)用restful接口,所以還要研究一番,自然也是查閱了一些資料。
分析:這個(gè)問(wèn)題與模塊之間的調(diào)用不同,比如我有兩個(gè)模塊front end 和back end,front end提供前臺(tái)展示,back end提供數(shù)據(jù)支持。之前使用過(guò)Hession去把back end提供的服務(wù)注冊(cè)成遠(yuǎn)程服務(wù),在front end端可以通過(guò)這種遠(yuǎn)程服務(wù)直接調(diào)到back end的接口。但這對(duì)于一個(gè)公司自己的一個(gè)項(xiàng)目耦合性比較高的情況下使用,沒(méi)有問(wèn)題。但是如果給客戶(hù)注冊(cè)這種遠(yuǎn)程服務(wù),似乎不太好,耦合性太高。所以就考慮用一下方式進(jìn)行處理。
一、HttpClient
HttpClient大家也許比較熟悉但又比較陌生,熟悉是知道他可以遠(yuǎn)程調(diào)用比如請(qǐng)求一個(gè)URL,然后在response里獲取到返回狀態(tài)和返回信息,但是今天講的稍微復(fù)雜一點(diǎn),因?yàn)榻裉斓闹黝}是HTTPS,這個(gè)牽涉到證書(shū)或用戶(hù)認(rèn)證的問(wèn)題。
確定使用HttpClient之后,查詢(xún)相關(guān)資料,發(fā)現(xiàn)HttpClient的新版本與老版本不同,隨然兼容老版本,但已經(jīng)不提倡老版本是使用方式,很多都已經(jīng)標(biāo)記為過(guò)時(shí)的方法或類(lèi)。今天就分別使用老版本4.2和最新版本4.5.3來(lái)寫(xiě)代碼。
老版本4.2
需要認(rèn)證
在準(zhǔn)備證書(shū)階段選擇的是使用證書(shū)認(rèn)證
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 { // 獲得密匙庫(kù) 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")); // 密匙庫(kù)的密碼 trustStore.load(instream, "password".toCharArray()); // 注冊(cè)密匙庫(kù) this.socketFactory = new SSLSocketFactory(trustStore); // 不校驗(yàn)域名 socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } }
跳過(guò)認(rèn)證
在準(zhǔn)備證書(shū)階段選擇的是跳過(guò)認(rèn)證
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 { // 跳過(guò)證書(shū)驗(yàn)證 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; } }; // 設(shè)置成已信任的證書(shū) ctx.init(null, new TrustManager[] { tm }, null); // 穿件SSL socket 工廠(chǎng),并且設(shè)置不檢查host名稱(chēng) this.socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } }
總結(jié)
現(xiàn)在發(fā)現(xiàn)這兩個(gè)類(lèi)都繼承了同一個(gè)類(lèi)HTTPSClient,并且HTTPSClient繼承了DefaultHttpClient類(lèi),可以發(fā)現(xiàn),這里使用了模板方法模式。
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 返回當(dāng)前實(shí)例 * @throws Exception */ public HTTPSClient init() throws Exception { this.prepareCertificate(); this.regist(); return this; } /** * 準(zhǔn)備證書(shū)驗(yàn)證 * * @throws Exception */ public abstract void prepareCertificate() throws Exception; /** * 注冊(cè)協(xié)議和端口, 此方法也可以被子類(lèi)重寫(xiě) */ protected void regist() { ClientConnectionManager ccm = this.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, socketFactory)); } }
下邊是工具類(lèi)
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) { // 設(shè)置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 { // 設(shè)置參數(shù) 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); } } } }
然后是測(cè)試類(lèi):
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
需要認(rèn)證
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 { // 獲得密匙庫(kù) 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 { // 密匙庫(kù)的密碼 trustStore.load(instream, "password".toCharArray()); } finally { instream.close(); } SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, TrustSelfSignedStrategy.INSTANCE) .build(); this.connectionSocketFactory = new SSLConnectionSocketFactory(sslcontext); } }
跳過(guò)認(rèn)證
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 { // 跳過(guò)證書(shū)驗(yàn)證 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; } }; // 設(shè)置成已信任的證書(shū) ctx.init(null, new TrustManager[] { tm }, null); this.connectionSocketFactory = new SSLConnectionSocketFactory(ctx); } }
總結(jié)
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 返回當(dāng)前實(shí)例 * @throws Exception */ public CloseableHttpClient init() throws Exception { this.prepareCertificate(); this.regist(); return this.client; } /** * 準(zhǔn)備證書(shū)驗(yàn)證 * * @throws Exception */ public abstract void prepareCertificate() throws Exception; /** * 注冊(cè)協(xié)議和端口, 此方法也可以被子類(lèi)重寫(xiě) */ protected void regist() { // 設(shè)置協(xié)議http和https對(duì)應(yīng)的處理socket鏈接工廠(chǎng)的對(duì)象 Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", this.connectionSocketFactory) .build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpClients.custom().setConnectionManager(connManager); // 創(chuàng)建自定義的httpclient對(duì)象 this.client = HttpClients.custom().setConnectionManager(connManager).build(); // CloseableHttpClient client = HttpClients.createDefault(); } }
工具類(lèi):
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) { // 設(shè)置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 { // 設(shè)置參數(shù) 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); } } } }
測(cè)試類(lèi):
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); } }
結(jié)果:
<?xml version="1.0" encoding="utf-8"?>
<token>RxitF9//7NxwXJS2cjIjYhLtvzUNvMZxxEQtGN0u07sC9ysJeIbPqte3hCjULSkoXPEUYGUVeyI9jv7/WikLrzxYKc3OSpaTSM0kCbCKphu0TB2Cn/nfzv9fMLueOWFBdyz+N0sEiI9K+0Gp7920DFEncn17wUJVmC0u2jwvM5FAjQKmilwodXZ6a0Dq+D7dQDJwVcwxBvJ2ilhyIb3pr805Vppmi9atXrVAKO0ODa006wEJFOfcgyG5p70wpJ5rrBL85vfy9WCvkd1R7j6NVjhXgH2gNimHkjEJorMjdXW2gKiUsiWsELi/XPswao7/CTWNwTnctGK8PX2ZUB0ZfA==</token>
二、HttpURLConnection
三、Spring的RestTemplate
其它方式以后補(bǔ)充
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
springBoot不同module之間互相依賴(lài)的實(shí)現(xiàn)
本文主要介紹了springBoot不同module之間互相依賴(lài)的實(shí)現(xiàn),不同模塊之間的依賴(lài)通常是通過(guò)Maven或Gradle來(lái)管理的,下面就來(lái)介紹一下如何實(shí)現(xiàn),感興趣的可以了解一下2024-08-08詳解Java面試官最?lèi)?ài)問(wèn)的volatile關(guān)鍵字
這篇文章主要介紹了詳解Java面試官最?lèi)?ài)問(wèn)的volatile關(guān)鍵字,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01spring-mvc/springboot使用MockMvc對(duì)controller進(jìn)行測(cè)試
這篇文章主要介紹了spring-mvc/springboot使用MockMvc對(duì)controller進(jìn)行測(cè)試,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-11-11從零開(kāi)始搭建springboot+springcloud+mybatis本地項(xiàng)目全過(guò)程(圖解)
這篇文章主要介紹了從零開(kāi)始搭建springboot+springcloud+mybatis本地項(xiàng)目全過(guò)程(圖解),本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01Java實(shí)現(xiàn)簡(jiǎn)單連連看游戲
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)簡(jiǎn)單連連看游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05Java經(jīng)驗(yàn)點(diǎn)滴:類(lèi)注釋文檔編寫(xiě)方法
Java經(jīng)驗(yàn)點(diǎn)滴:類(lèi)注釋文檔編寫(xiě)方法...2006-12-12Java21增強(qiáng)對(duì)Emoji表情符號(hào)處理示例詳解
這篇文章主要為大家介紹了Java21增強(qiáng)對(duì)Emoji表情符號(hào)處理示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11Springboot 如何使用 SaToken 進(jìn)行登錄認(rèn)證、權(quán)限管理及路由規(guī)則接口攔截
Sa-Token 是一個(gè)輕量級(jí) Java 權(quán)限認(rèn)證框架,主要解決:登錄認(rèn)證、權(quán)限認(rèn)證、單點(diǎn)登錄、OAuth2.0、分布式Session會(huì)話(huà)、微服務(wù)網(wǎng)關(guān)鑒權(quán) 等一系列權(quán)限相關(guān)問(wèn)題,這篇文章主要介紹了Springboot 使用 SaToken 進(jìn)行登錄認(rèn)證、權(quán)限管理以及路由規(guī)則接口攔截,需要的朋友可以參考下2024-06-06