초록 : 최근에 고객에게 편안한 API 인터페이스를 제공 해야하는 요구 사항이 있습니다. QA는 Testing을 위해 Postman을 사용하지만 Postman의 테스트 인터페이스는 비슷하지만 Java 통화와 다릅니다. 그래서 저는 RESTFUL API 인터페이스를 직접 테스트하는 프로그램을 작성하고 싶습니다. HTTPS를 사용하므로 HTTP의 처리도 고려해야합니다. Java를 사용하여 처음으로 Restful Interface를 호출 했으므로 여전히 공부해야하므로 자연스럽게 정보를 참조했습니다.
분석 :이 문제는 모듈 간의 통화와 다릅니다. 예를 들어, 프론트 엔드와 백엔드의 두 개의 모듈이 있으며 프론트 엔드는 프론트 엔드 디스플레이를 제공하며 백엔드는 데이터 지원을 제공합니다. Hession을 사용하여 백엔드에서 제공하는 서비스를 원격 서비스로 등록했습니다. 프론트 엔드 에서이 원격 서비스는 이러한 종류의 원격 서비스를 통해 백엔드 인터페이스에 직접 조정할 수 있습니다. 그러나 이것은 회사가 자체 프로젝트가 크게 결합 될 때 사용하는 데 문제가되지 않습니다. 그러나 이러한 원격 서비스를 고객에게 등록하면 좋지 않은 것처럼 보이고 커플 링이 너무 높습니다. 그래서 다음 방법을 사용하는 것을 고려합니다.
1. httpclient
모든 사람은 httpclient에 익숙 할 수 있지만 그것에 익숙하지 않습니다. 예를 들어 원격으로 호출하고 URL을 요청한 다음 응답에서 반환 상태를 가져오고 정보를 반환 할 수 있기 때문에 익숙합니다. 그러나 오늘날의 주제는 HTTPS이므로 인증서 또는 사용자 인증 문제가 포함되어 있기 때문에 오늘은 조금 더 복잡합니다.
HTTPClient를 사용하여 관련 정보를 검색 한 후 새 버전의 httpclient가 이전 버전과 다르고 이전 버전과 호환되는 것을 발견했지만 더 이상 이전 버전을 사용하는 것이 권장되지 않습니다. 많은 방법이나 클래스가 구식으로 표시되었습니다. 오늘날, 우리는 기존 버전 4.2와 최신 버전 4.5.3을 사용하여 각각 코드를 작성할 것입니다.
오래된 버전 4.2
인증 필요성
인증서 인증 사용은 인증서 준비 단계에서 선택됩니다.
패키지 com.darren.test.https.v42; import java.io.file; import java.io.fileInputStream; java.security.keystore 가져 오기; import org.apache.http.conn.ssl.sslsocketfactory; 공개 클래스 httpsCertifiedClient는 httpsclient {public httpsCertifiedClient () {} @override public void repareCertificate () 예외 {// 키 라이브러리 keystore trustStore = keystore.getInstance (keystore.getDefaultType ()); fileInputStream input = new FileInputStream (새 파일 ( "C : /users/zhda6001/downloads/software/xxx.keystore")); // fileInputStream input = new FileInputStream (새 파일 ( "C : /users/zhda6001/downloads/xxx.keystore")); // 키 라이브러리의 비밀번호 TrustStore.load (Instream, "Password".tochararray ()); // 키 라이브러리를 등록 this.SocketFactory = New SSLSocketFactory (TrustStore); // 도메인 이름 SocketFactory.SetHostNameVerifier (sslsocketfactory.alow_all_hostname_verifier)를 확인하지 마십시오. }}인증을 건너 뛰십시오
인증서 준비 단계에서 인증을 건너 뛰는 옵션은 다음과 같습니다.
패키지 com.darren.test.https.v42; java.security.cert.certificateException 가져 오기; 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; 공개 클래스 httpsTrustClient는 httpsclient {public httpstrustClient () {} @override public void repareCertificate () 예외를 {// 스킵 인증서 확인 sslcontext ctx = sslcontext.getInstance ( "tls"); x509trustmanager tm = new x509trustmanager () {@override public void checkclientTrusted (x509certificate [] 체인, String authtype) 추력 증명서 exception {} @override public void checkserverTrusted (x509certificate, string upplial) x509certificate [] getAcceptedIssuers () {return null; }}; // 신뢰할 수있는 인증서 CTX.init (NULL, NEW TRUSTMANAGER [] {TM}, NULL)로 설정합니다. // SSL Socket Factory를 넣고 호스트 이름을 확인하지 않도록 설정 this.socketfactory = new sslsocketfactory (ctx, sslsocketfactory.alow_all_hostname_verifier); }}요약
이제 두 클래스 모두 동일한 클래스 httpsclient를 상속 받고 HttpsClient는 defaulthttpclient 클래스를 상속합니다. 템플릿 메소드 패턴이 여기에서 사용된다는 것을 알 수 있습니다.
패키지 com.darren.test.https.v42; import org.apache.http.conn.clientConnectionManager; import org.apache.http.conn.scheme.scheme; import org.apache.http.conn.ssl.sslsocketfactory; import org.apache.http.impl.client.defaulthttpclient; 공개 초록 클래스 httpsclient는 defaulthttpclient를 확장합니다. / ** * httpsclient 초기화 * * @return 현재 인스턴스를 반환 * @throws 예외 */ public httpsclient init ()는 예외 {this.preparecertificate (); this.regist (); 이것을 반환하십시오; } / ** * 증명서 검증 준비 * * @throws 예외 * / public acpract void repareCertificate ()는 예외를 던집니다. / *** 레지스터 프로토콜 및 포트,이 메소드는 서브 클래스에 의해 다시 작성 될 수 있습니다*/ Protected void regist () {clientConnectionManager ccm = this.getConnectionManager (); schemeregistry sr = ccm.getSchemeregistry (); sr.register (새로운 체계 ( "https", 443, socketfactory)); }} 아래는 도구 클래스입니다
패키지 com.darren.test.https.v42; java.util.arraylist 가져 오기; Java.util.list 가져 오기; java.util.map import; java.util.set import; 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; 공개 클래스 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) 예외 {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)는 예외 {string result = null; httppost httppost = 새로운 httppost (url); Setheader (httppost, paramheader); setbody (httppost, parambody, charset); httpresponse response = httpsclient.execute (httppost); if (inentity! = null) {httpentity inentity = response.getentity (); if (inentity! = null) {result = entityutils.toString (분노, 숯); }} 반환 결과; } public static string doget (httpsclient httpsclient, String URL, Map <String, String> Paramheader, Map <String, String> parambody) 예외 {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)는 예외 {String result = null; httpget httpget = new httpget (url); Setheader (httpget, paramheader); httpresponse response = httpsclient.execute (httpget); if (response! = null) {httpentity fenentity = response.getentity (); if (inentity! = null) {result = entityutils.toString (분노, 숯); }} 반환 결과; } private static void setheader (httprequestbase request, map <string, string> paramheader) {// set header if (paramheader! = null) {set <string> keyset = paramheader.keyset (); for (문자열 키 : 키 세트) {request.addheader (key, paramheader.get (key)); }}} private static void setbody (httppost httppost, map <string, string> parambody, string charset) 예외 {// 파라미터를 설정 if (parambody! = null) {list <namevaluepair> list = new arraylist <namevaluepair> (); <string> keyset = parambody.keyset (); for (문자열 키 : Keyset) {list.add (new BasicNameValuePair (key, parambody.get (key))); } if (list.size ()> 0) {urlencodedformentity entity = 새로운 urlencodedformentity (list, charset); httppost.setentity (엔티티); }}}} 그런 다음 테스트 클래스가 있습니다.
패키지 com.darren.test.https.v42; java.util.hashmap import; java.util.map import; 공개 클래스 httpsclientTest {public static void main (String [] args)은 예외 {httpsclient httpsclient = null; httpsclient = new httpstrustclient (). init (); // httpsclient = new httpsCertifiedClient (). init (); 문자열 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", "[email protected]"); parambody.put ( "client_secret", "p@ssword_1"); 문자열 결과 = httpsclientutil.dopost (httpsclient, url, paramheader, parambody); // 문자열 result = httpsclientutil.doget (httpsclient, url, null, null); System.out.println (결과); }} 반품 정보 :
<? xml 버전 = "1.0"encoding = "utf-8"?>
<TOKEN> JKF8RL0SW+SKKFLJ8RBKI5HP1BEQKK8PRCUTZPPBINQMYKRMXY1KWCJMCFT191ZPP88V1AGHW8OYNWJEYS 0axplugax89ejcownbikcc1uvfyesxhlktcjqyufivjevhreqxjphnclqywp+xse5od9x8vkkk7inntmrzqk7ybtz /e3u7gswm/5cvahfl6o9req9cwpxavznohyvnxsohszdo+bxatxxa1xpedpledly/8h/uap4n4dlzdjj3b8t1xh+crriom opxf7c5wkhtokeoexw+xopqkkkkkkkkkkkkwwjppugiifwf/paqwg+juosvt7qgdpv8pmwj9dwewjtdxgudg == </token>
새로운 버전 4.5.3
인증 필요성
패키지 com.darren.test.https.v45; import java.io.file; import java.io.fileInputStream; java.security.keystore 가져 오기; import javax.net.ssl.sslcontext; import org.apache.http.conn.ssl.sslconnectionsocketfactory; import org.apache.http.conn.ssl.sslconnectionsocketfactory; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.ssl.sslcontexts; 공개 클래스 httpsCertifiedClient는 httpsclient {public httpsCertifiedClient () {} @override public void repareCertificate () 예외 {// 키 라이브러리 keystore trustStore = keystore.getInstance (keystore.getDefaultType ()); fileInputStream instream = new FileInputStream (새 파일 ( "C : /users/zhda6001/downloads/software/xxx.keystore")); // fileInputStream instream = new FileInputStream (새 파일 ( "C : /users/zhda6001/downloads/xxx.keystore")); Try {// 키 라이브러리의 비밀번호 TrustStore.load (Instream, "Password".tochararray ()); } 마침내 {enterstream.close (); } sslcontext sslcontext = sslcontexts.custom (). loadTrustMaterial (TrustStore, TrustSelfSignedStrategy.instance) .Build (); this.connectionSocketFactory = 새로운 SSLConnectionSocketFactory (SSLContext); }}인증을 건너 뛰십시오
패키지 com.darren.test.https.v45; java.security.cert.certificateException 가져 오기; 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; 공개 클래스 httpsTrustClient는 httpsclient {public httpstrustClient () {} @override public void repareCertificate () 예외를 {// 스킵 인증서 확인 sslcontext ctx = sslcontext.getInstance ( "tls"); x509trustmanager tm = new x509trustmanager () {@override public void checkclientTrusted (x509certificate [] 체인, String authtype) 추력 증명서 exception {} @override public void checkserverTrusted (x509certificate, string upplial) x509certificate [] getAcceptedIssuers () {return null; }}; // 신뢰할 수있는 인증서로 설정 CTX.init (NULL, NEW TRUSTMANAGER [] {TM}, NULL); this.connectionSocketFactory = 새로운 SSLConnectionSocketFactory (CTX); }}요약
패키지 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; 공개 초록 클래스 httpsclient 확장 httpclientBuilder {private closeblehttpclient client; 보호 된 ConnectionSocketFactory ConnectionSocketFactory; / ** * httpsclient 초기화 * * @return 현재 인스턴스를 반환 * @Throws Exception */ public closeblehttpclient init ()는 예외 {this.preparecertificate (); this.regist (); 이를 반환하십시오 .Client; } / ** * 증명서 검증 준비 * * @throws 예외 * / public acpract void repareCertificate ()는 예외를 던집니다. / *** 레지스터 프로토콜 및 포트,이 메소드는 서브 클래스*/ Protected void regist () {// 소켓 링크 링크 팩토리 레지스트리 <connectionsocketfactory> socket factoryregistry = registryBuilder를 처리하는 프로토콜 http 및 https에 해당하는 객체를 설정할 수도 있습니다. 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 (); }} 도구 :
패키지 com.darren.test.https.v45; java.util.arraylist 가져 오기; Java.util.list 가져 오기; java.util.map import; java.util.set import; 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; 공개 클래스 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) 예외 {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)는 예외 {String result = null; httppost httppost = 새로운 httppost (url); Setheader (httppost, paramheader); setbody (httppost, parambody, charset); httpresponse 응답 = httpclient.execute (httppost); if (inentity! = null) {httpentity inentity = response.getentity (); if (inentity! = null) {result = entityutils.toString (분노, 숯); }} 반환 결과; } public static string doget (httpclient httpclient, String URL, Map <String, String> Paramheader, Map <String, String> parambody) 예외 {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)는 예외 {String result = null; httpget httpget = new httpget (url); Setheader (httpget, paramheader); httpresponse 응답 = httpclient.execute (httpget); if (response! = null) {httpentity fenentity = response.getentity (); if (inentity! = null) {result = entityutils.toString (분노, 숯); }} 반환 결과; } private static void setheader (httprequestbase request, map <string, string> paramheader) {// set header if (paramheader! = null) {set <string> keyset = paramheader.keyset (); for (문자열 키 : 키 세트) {request.addheader (key, paramheader.get (key)); }}} private static void setbody (httppost httppost, map <string, string> parambody, string charset) 예외 {// 파라미터를 설정 if (parambody! = null) {list <namevaluepair> list = new arraylist <namevaluepair> (); <string> keyset = parambody.keyset (); for (문자열 키 : Keyset) {list.add (new BasicNameValuePair (key, parambody.get (key))); } if (list.size ()> 0) {urlencodedformentity entity = 새로운 urlencodedformentity (list, charset); httppost.setentity (엔티티); }}}}}} 테스트 클래스 :
패키지 com.darren.test.https.v45; java.util.hashmap import; java.util.map import; import org.apache.http.client.httpclient; 공개 클래스 httpsclientTest {public static void main (String [] args)은 예외 {httpclient httpclient = null; // httpclient = new httpsTrustClient (). init (); httpclient = new httpsCertifiedClient (). init (); 문자열 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", "[email protected]"); parambody.put ( "client_secret", "p@ssword_1"); 문자열 결과 = httpsclientutil.dopost (httpclient, url, paramheader, parambody); // 문자열 result = httpsclientutil.doget (httpsclient, url, null, null); System.out.println (결과); }} 결과:
<? xml 버전 = "1.0"encoding = "utf-8"?>
<TOKEN> RXITF9 // 7NXWXJS2CJIJYHLTVZNVMZXXEQTGN0U07SC9YSJEIBPQTE3HCJULSKOXOXPEUYGUVEY9JV7/WI klrzxykc3ospatsm0kcbckphu0tb2cn/nfzv9fmlueowfbdyz+n0seiik+0gp7920dfencn17wujvmc0u2jwvm5fa JQKMILWODXZ6A0DQ+D7DQDJWVCWXBVJ2ILHYIB3PR805VPPMI9ATXRVAKO0ODA006WEJFOFCGYG5P70WPJ5RRBL85V fy9wcvkd1r7j6nvjhxgh2gnimhkjejormjdxw2gkiusiwseli/xpswao7/ctwnwtnctgk8px2zub0zfa == </token>
2. httpurlconnection
3. 봄의 resttemplate
다른 방법은 나중에 보충됩니다
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.