要約:最近、顧客にいくつかのRestful APIインターフェイスを提供するための要件があります。 QAはテストにPostmanを使用しますが、Postmanのテストインターフェイスは類似していますが、Javaコールと同じではありません。そのため、自分でRESTFUL APIインターフェイスをテストするプログラムを作成したいと思います。 HTTPSを使用するため、HTTPSの処理も考慮する必要があります。 Javaを使用してRestful Interfaceを初めて呼び出していたので、まだ勉強する必要があるので、自然にいくつかの情報を参照しました。
分析:この問題は、モジュール間の呼び出しとは異なります。たとえば、フロントエンドとバックエンドの2つのモジュールがあります。 FrontEndはFrontEndディスプレイを提供し、バックエンドはデータサポートを提供します。 Hessionを使用して、バックエンドが提供するサービスをリモートサービスとして登録しました。フロントエンド側では、このリモートサービスをバックエンドインターフェイスに直接調整できます。しかし、これは、企業が独自のプロジェクトが非常に結合されている場合に使用するのに問題はありません。ただし、そのようなリモートサービスを顧客に登録すると、良くないようで、結合が高すぎます。したがって、次の方法を使用することを検討します。
基本的な紹介
RESTFULインターフェイスの呼び出しでは、フロントエンドは一般にAJAXコールを使用し、バックエンドはより多くの方法を使用できます。
今回は、3つのタイプが導入されています。
1.httpurlconnectionの実装
2.httpclient実装
3。Springのレストテンプレート
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; import java.security.keystore; import org.apache.http.conn.ssl.sslsocketafctory; public class httpsifiedsclients httpsclclcclccl. {} @Override public void preparecertificate()throws Exception {//キーライブラリキーストアトラストストア= keyStore.getInstance(keystore.getDefaultType()); fileinputStream = new fileinputStream(new file(new file( "c:/users/zhda6001/dowdowds/softsputwear"); input = 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_al認定をスキップします
証明書の準備段階で認証をスキップするオプションは、
パッケージcom.darren.test.https.v42; Import java.security.cert.certificateException; Import java.security.cert.x509Certificate; Import javax.net.ssl.sslcontext; Import javax.net.sl.trustmanager; import Javax.net. org.apache.http.conn.ssl.sslsocketfactory; public class httpstrustclient extends httpsclient {public httpstrustclient(){} @override public void preparecertificate()throws Exception {// SSLCONTEXT CTX = SKIP証明書の検証{// SSLCONTEXT CTX = SKIP sslcontext.getInstance( "tls"); x509trustmanager tm = new x509trustmanager(){@Override public void checkClientTrusted(x509certificate [] chain、string authytype)Sthrows certifaringexception {} @Override public void authertrusted(x5tectifawsed(x5tectifakes) CertificateException {} @Override public x509Certificate [] getAcceptedissuers(){return null;}}; //信頼できる証明書ctx.init(null、new Trustmanager [] {Tm}、null); // sslsocketfactory.allow_all_hostname_verifier);}}要約します
現在、両方のクラスが同じクラスhttpsclientを継承し、httpsclientがdefulthttpclientクラスを継承することがわかります。ここでは、テンプレートメソッドパターンが使用されていることがわかります。
パッケージcom.darren.test.https.v42; Import org.apache.http.conn.clientConnectionManager; Import org.apache.http.conn.scheme.scheme; Import org.apache.http.conn.ssl.slsocketory; Import; org.apache.http.impl.client.defaulthttpclient; public abstract class httpsclientはdefaulthttpclientを拡張します{Protected sslsocketyfactory socketyfactory;/** *初期化httpsclient * * @return return exception */public httpsclient Intain {this.preparecertificate(); this.regist(); return this;}/*** @throws exception*/public abstract void preparecertificate()throws exception;/***登録プロトコルとポートを登録することもできます。 this.getConnectionManager(); Schemeregistry sr = ccm.getschemeregistry(); sr.register(new Scheme( "https"、443、SocketFactory));}}}以下はツールクラスです
パッケージ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_charse d; "utf-charset = httpsclient、string url、map <string、string> paramheader、map <string、string> parambody)slows {return dopost(httpsclient、url、paramheader、parambody、default_charset);} public static string dopost(httpsclient httpsclient、string> string> paramhead> string> parmhead、string> paramhead、string {string result = null; httppost httppost = new httppost(url); setheader(httppost、paramheader); setbody(httppost、parambody、charset); httpsclient.execute(httppost); httpsclient.execute(httppost); if (resentity!= null){result = entityutils.toString(resentity、charset);}} return result;} public static string doget(httpsclient httpsclient、string url、map <string、string> paramhead、map <<string> string> parambody)スロー例外static string doget(httpsclient、httpsclient、string url、map <string、string> paramheader、map <string、string> parambody、string charset)throws {string result = null; httpget httpget = new httpget(url); setheader(httpget、htppresponse response = httpsclient.execute(httpget); if(response!= null){httpentity resentity = response.getentity(); if(resentity!= null){result = entityutils.tostring(resentity、charset);}} return result result;} private void setheAder {//ヘッダーを設定するif(paramheader!= null){set <string> keyset = paramheader.keyset(); for(string key:keyset){request.addheader(key、paramheader.get(key));}}} private static void set setbody(httppost httppost、map <string> sit> sitring> sitring> string> sit> string> sit> string (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)); urlencodedformentity(list、charset); httppost.setentity(entity);}}}}}}次に、テストクラスがあります。
パッケージcom.darren.test.https.v42; import java.util.hashmap; import java.util.map; public class httpsclienttest {public static void main(string [] args)throws {httpsclient httpsclient = null; httpstrustclient()。init(); // httpsclient = new httpscertifiedClient()。init(); string url = "https://1.2.6.2:8011/xxx/api/gettoken"he//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"); string result result = httpsclientutil.dopost(httpsclient(httpsclient、url、paramodeer、parambody); httpsclientutil.doget(httpsclient、url、null、null); System.out.println(result);}}返品情報:
<?xml version = "1.0" encoding = "utf-8"?> <token> jkf8rl0sw+skkflj8rbki5hp1beqk8prcutzppbinqmykrmxy1kwcjmcft191zpp88vvv1aghw8oynwjeys 0AXPLUGAX89EJCOWNBIKCC1UVFYESXHLKTCJQYUFIVJEVHREQXJPHNCLQYWP+XSE5OD9X8VKFKK7INNTMRZQK7YBTZ /e3u7gswm/5cvahfl6o9req9cwpxavznohyvnxsohszdo+bxatxxa1xpedly/8h/uap4n4dlzdjj3b8t1xh+crriom OPXF7C5WKHTOKEOEXW+XOPQKKKSX5CKWWJPPUGIIFWF/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.sslconnectionsocketfactory; Import org.apache.http.conn.ssl.trustselfsignededstrategy; import org.apache.http.ssl.sslcontexts; public class httpscerient extentifieds httpsclcclccl() {} @Override public void preparecertificate()throws Exception {//キーライブラリキーストアトラストストア= keystore.getInstance(keystore.getDefaultType()); fileinputStream = new FileInputStream(new File( "c:/users/zhdaers/zhda6001/dowdlowdlowed/dowddlowe fileInputStream entream = new fileInputStream(new File( "C:/USERS/ZHDA6001/DOWNLOADS/XXX.KEYSTORE")); try {//キーライブラリトラストストアのパスワード(instream、 "password" .tochararray());} fullly {instream.close();} sslcontext sslcontext = sslcontexts.custom()。loadtrustmaterial()。これ認定をスキップします
com.darren.test.https.v45 org.apache.http.conn.ssl.sslconnectionsocketfactory; public class httpstrustclientはhttpsclient(){} @override public void preateficate()throws experionce(){//証明書の確認Slcontex sslcontext.getInstance( "tls"); x509trustmanager tm = new x509trustmanager(){@Override public void checkClientTrusted(x509certificate [] chain、string authytype)Sthrows certifaringexception {} @Override public void authertrusted(x5tectifawsed(x5tectifakes) certiffertexception {} @override public void checkservertrusted(x509certificate [] chain、string authtype)Sthrows excermentexception {} @override public x509certificate [] getCeptedissuers(){return null;}}; null); this.ConnectionSocketFactory = new SSLConnectionSocketFactory(ctx);}}}要約します
パッケージcom.darren.test.https.v45; Import org.apache.http.config.registry; Import org.apache.http.config.registrybuilder; Import org.apache.http.conn.sockenceSocketaffactory; inmolg.htp.conctornections.contp.conters.contpn.contpn.contcontのintalcnections.contp.contontacknectionsfactory 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.poolinghttpclingnectnectnectnectn.pulenthnectionhttp.client.httpclientsクラスhttpsclientはhttpclientbuilder {private closeablehttpclientクライアント;保護されたConnectionSockentFactory ConnectionSocketAcketFactory;/** *初期化HttpsClient * * @return return return * @throws例外 */public closeablehttpclient init()throws {this.preparecertificate(); this.client;}/***証明書確認を準備** @スロウ例外*/public abstract void preperecertificate()throws exception;/***登録プロトコルとポート、このメソッドはサブクラス*/保護されたvoid regist(){//プロトコルhttpとhttps recotis sockets soction soction sockets httpsに対応するオブジェクトを設定することもできます。 SocketFactoryRegistry = registryBuilder。<ConnectionSocketFactory> create().register( "http"、plainConnectionSocketFactory.instance).register( "https"、this.connectionsocketfactory).build(); build(); poolinghttpclientconnectionnaction connmanager = new New poolinghttpclientConnectionManager(socketFactoryRegistry); httpclients.custom()。setConnectionManager(connmanager); //カスタムhttpclientオブジェクトthis.client = httpclients.custom()。setconnectionmanager(connmanager()。 httpclients.createdefault();}}ツール:
パッケージ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.client.methods.httpget; import apach.htppt.cltp.cltp.cltp. 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 default = "" utf-charset = httpclient、string url、map <string、string> paramheader、map <string、string> parambody)slows {return dopost(httpclient、url、paramheader、parambody、default_charset);} public static string dopost(httpclient httpclient、string> string> paramhead> string> paramhead、string> parmhead、string> parmhead、string> string> parmheader、string {string result = null; httppost httppost = new httppost(url); setheader(httppost、paramheader); setbody(httppost、parambody、charset); httpclient.execute(httppost); httpclient.execute(httppost); if(httpentity) (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 {string result = null; httpget httpget = new httpget(URL); httpclient.execute(httpget); if(response!= null){httpentity resentity = response.getEntity(); if(resentity!= null){result = entityutils.tostring(resentity、charset);}} return resoult {//ヘッダーを設定if(paramheader!= null){set <string> keyset = paramheader.keyset(); (文字列キー:keyset){request.addheader(key、paramheader.get(key));}}}} private static void setbody(httppost httppost、map <string、string> paramody、string charset)throws {// set parameters if(parambody! ArrayList <NameValuePair>(); set <string> keyset = parambody.keyset(); for(string key:keyset){list.add(new basicnamevaluepair(key、paramody.get(key));} charset); httppost.setentity(entity);}}}}テストクラス:
com.darren.test.https.v45 null; // httpclient = new httpstrustClient()。init(); httpclient = new httpscertifiedClient()。init(); string url = "https://1.2.6.2:8011/xxx/api/gettoken"he//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]"); parmbody.put( "client_secret"); 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 // 7nxwxjs2cjijyhltvzunvmzxxxeqtgn07sc9yibpqte3hcjulskoxpeuyguveyii9jv7/wi klrzxykc3ospatsm0kcbckphu0tb2cn/nfzv9fmlueowfbdyz+n0seii9k+0gp7920dfencn17wujvmc0u2jwvm5fa jqkmilwodxzz6a0dq+d7dqdjwvcwxbvj2ilhyib3ppl805vppmi9atxrvako0oda006wejfofcgygg5p70wpj5rrbl85vvv fy9wcvkd1r7j6nvjhxgh2gnimhkjejormjdxw2gkiusiwseli/xpswao7/ctwnwtnctgk8px2zub0zfa == </token>
2。HTTPURLCONNECTION
@controllerpublic class Restfulaction {@autowired private userservice userservice; // @RequestMapping(value = "put/{param}"、method = requestmethod.put)public @responsebody string put( @pathvariable string param){return "put:" + param;} requestmethod.post)public @responsebody string post( @pathvariable string param、string id、string name){system.out.println( "id:"+id); system.out.println( "name:"+name); return "post:"+param;} // delete @requestmapping(valuation/valut = "delete/{delete/{delete/{param} dde string delete( @pathvariable string param){return "delete:" + param;} // @requestmapping(value = "get/{param}"、method = requestmethod.get)public @responsebody string get( @pathvariable string param){return "get:" + param;} // "dealcon/{param}")public @responsebody string dealcon( @pathvariable string param){try {string url = "http:// localhost:8080/tao-manager-web/"; url+=(param+"/xxx"); url retserviceurl = new url(url); htpuncontyurl(url); (httpurlconnection)restserviceurl.openconnection(); // param delect httpconnection.setRequestMethod(); // httpconnection.setRequestProperty( ");" post ");" post ");出力スイッチhttpconnection.setDooutput(true); // httpconnection.setDoinput(true); //パラメーター文字列input = "&id ="+ urlencoder.encode( "abc"、 "utf-8"); input+ = "&name ="+ urlencoder.encode( "ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh httpconnection.getOutputStream(); outputStream.write(input.get.getBytes()); outputStream.flush();} if(httpconnection.getResponseCode()!= 200){throw new runtimeexcection( "http get request failed with error code:" + " + httpconnection.getResponseCode());} BufferedReader ResponseBuffer = new BufferedReader((httpconnection.getInputStream())); System.out.println( "server: /n"); {system.out.println(output);} httpconnection.disconnect();} catch(malformedurlexception e){e.printstacktrace();} catch(ioexception e){e.printstacktrace();} return "success";}}}}}3。Springのレストテンプレート
springmvc.xmlが追加されました
<! - RESTTEMPLATEを設定 - > <! - HTTPクライアントファクトリー - > <Bean ID = "httpclientFactory"> <プロパティ名= "connecttimeout" value = "10000" /> <プロパティ名= "readtimeout" value " /> < /bean> <! - resttemplate-> <bean id =" reatetemplate "> < ref = "httpclientFactory" /> < /bean>
コントローラ
@ControllollerPublic class RestTemplateAction {@Autowired PrivateRestTemplate Template; @RequestMapping( "RESTTEM")public @ResponseBodyユーザーRESTTEM(ユーザーユーザー= null; // Find if( "get" .equals(method)){user = semplate.getForobject( 「http:// localhost:8080/tao-manager-web/get/{id}」、user.class、 "wuwuwuwu"); getForentity( "http:// localhost:8080/tao-manager-web/get/{id}"、user.class、 "wuwuwuwuwuuwu"); system.out.println(re.getstatuscode()); system.out.out.println(re.getBody(); ( "post" .equals(method)){httpheaders headers = new httpheaders(); headers.add( "x-auth-token"、uuid.randomuuid()。toString()); multivaluemap <string、string、string> postparameters = new linkedmultivaluemap <<string、pustring>; "ahhhhh"); postparameters.add( "name"、 "partialバージョン"); httpentity <multivaluemap <string、string >> requestentity = new httpentity <multivaluemap <string、string >>(postparameters、headers); "http:// localhost:8080/tao-manager-web/post/aaa"、requestentity、user.class); // delete} else if( "delete" .equals(method))) {template.delete( "http:// localhost:8080/tao-manager-web/delete/{id}"、 "aaa"); // modify} else if( "put" .equals(method))) {template.put( "http:// localhost:8080/tao-manager-web/put/{id}"、null、 "bbb");} return user;}}}上記は、JavaがRestful APIインターフェイスを呼び出す方法について簡単に説明するこの記事の内容全体です。私はそれが誰にでも役立つことを願っています。興味のある友人は、このウェブサイトで他のJava関連のトピックを引き続き参照できます。欠点がある場合は、それを指摘するためにメッセージを残してください。このサイトへのご支援をありがとうございました!