1つ。
1. httprequestutilsツールクラスを記述します。
パッケージcom.brainlong.framework.util.httpclient; net.sf.json.jsonobject; Import org.apache.commons.httpclient.httpstatus; import org.apache.httppresponse; import org.apache.http.client.methods.httpget; Import org.apache.http.client.methods.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.s.method org.apache.http.entity.stringentity; import org.apache.http.impl.client.defaulthttpclient; Import org.apache.http.util.entityutils; Import org.slf4j.logger; Import org.slf4j.loggerfactory; java.io.ioexception; Import java.net.urldeCoder;パブリッククラスhttprequestutils {private static logger logger = loggerfactory.getLogger(httprequestutils.class); // log/** * httppost * @param url path * @param jsonparamパラメーター * @return */public static jsonobject httppost(string url、jsonobject jsonparam){return httppost(url、jsonparam、false); } /*** post request* @param url urlアドレス* @param jsonparamパラメーター* @param noneedresponse result result* @return* /public static jsonobject httppost(string url、jsonobject jsonparam、boolean nowedresponse){//返品リクエストリクエストリクエストリクエストdefulthttpclient(); jsonobject jsonresult = null; httppost method = new httppost(url); try {if(null!= jsonparam){//中国の文字化け問題Stringentity Entity = new Stringentity(jsonparam.tostring()、 "utf-8"); entity.setContentenCoding( "utf-8"); entity.setContentType( "Application/JSON"); method.setEntity(エンティティ); } httpresponse result = httpclient.execute(method); url = urldecoder.decode(url、 "utf-8"); / **リクエストが正常に送信され、応答を受信しました**/ if(result.getStatusline()。getStatusCode()== 200){string str = ""; { / **サーバーによって返されたjson文字列データを読み取ります** / str = entityutils.toString(result.getEntity()); if(noneedResponse){return null; } / ** json文字列をjsonオブジェクトに変換** / jsonresult = jsonobject.fromobject(str); } catch(Exception e){logger.error( "投稿要求の提出が失敗しました:" + url、e); }}} catch(ioException e){logger.error( "投稿要求の提出失敗:" + url、e); } jsonresultを返します。 } /*** get request* @param url path* @return* /public static jsonobject httpget(string url){// get request Returns results jsonobject jsonresult = null; try {defaulthttpclient client = new defaulthttpclient(); // get request httpget request = new httpget(url); httpresponse応答= client.execute(request); / **リクエストは正常に送信され、応答を受け取りました**/ if(respons.getStatusline()。getStatusCode()== httpstatus.sc_ok){/ **サーバーによって返されたjson文字列データを読み取りました**/ string strensult = entityutils.tostring(response.getentity()); / ** JSON文字列をJSONオブジェクトに変換します**/ jsonResult = jsonobject.fromobject(strresult); url = urldecoder.decode(url、 "utf-8"); } else {logger.error( "request request Submissionが失敗しました:" + url); }} catch(ioException e){logger.error( "get request Submissionが失敗しました:" + url、e); } jsonresultを返します。 }}2。HTTPリクエストを送信するビジネスコードを書き込みます
3。MVC構成ファイル設定コントローラースキャンディレクトリ
<! - 自動スキャンとSCANのみ@Controller-> <Context:Component-ScanSycanベースパッケージ= "com.wiselong.multichannel" use-default-filters = "false"> <context = "annotation" expression = "org.springframework.tertype.controller"
4。HTTPリクエストを受信します
投稿リクエストを受け取ります
@controller@requestmapping(value = "/api/platform/exceptioncenter/excectioninfo")publicclassexceptioninfocontroller {// Inject @autowiredprivateexcenceptinginfobizexexceptincepsinfobiz; header*@returnjsonobject*/@requestmapping(value = "/create"、method = requestmethod.post)publicmodelandviewcreateexceptionfo(@requestbodystringRrequestbody、httpservletrequestRequest){jsonobjectjsonobject ct = jsonobject.fromobject(requestbody); comexceptionInfocomexceptionInfo = newcomexCeptionInfo(); comexceptionInfo.setProjectName(jsonObject。 getString( "ProjectName")); comexceptionInfo.settagname(jsonobject.getString( "projectname")); comexceptioninfo.settagname(jsonobject.getStr ing( "tagname")); exceptionInfobiz.insert(comexceptioninfo); //リクエスト結果を返すjsonobjectresult = newjsonobject(); result.put( "success"、 "true");Get Requestを受信します
@controller@requestmapping(value = "/api/platform/messagecenter/messages/sms")publicclasssmscontroller {@autowiredsmssmssmsssmssmsssendbiz;/***携帯電話番号とコンテンツを受信し、SMS送信テーブル*@paramrequestbodyリクエストメッセージにレコードを挿入header*@returnjsonobject*/@requestmapping(value = "/send"、method = requestmethod.get)publicModelandViewsendsms(@requestbodyStringRequestBody、httpservletrequestRequest){//リクエストURLとURLの後にパラメーターを取得しますstringurl = request.getRequesturl()+"?"+request.getqueryString(); url = buildrequesturl.decodeurl(url); stringtelephone = requestutils.getStringValue(request、 "電話e "); stringContent = requestutils.getStringValue(request、" content "); smssendbiz.insertttmsququ(電話、content); returnnewmodelandview(" "、responseutilshelper.jsonresult("、true));}}}}二。
得る
importjava.io.bufferedreader; importjava.io.ioexception; importjava.io.inputStream; importjava.io.inputStreamReader; importorg.apache.commons.httpclient.httpclient; import org.apache.commons.httpclient.httpmethod; importorg.apache.commons.httpclient.methods.getMethod; publicClassh_client_get {publicStaticVoidMain(String [] args)throwsioexcep tion{//new class object HttpClientclient=newHttpClient();//Use the GET method to interact with the URL server//HttpMethodmethod=newGetMethod("http://192.168.111.128/bak/[email protected]&passwor d = 1234567&re_password = 1234567&username = admin&nickname = admin "); httpmethodmethod = newgetmethod(" http://192.168.111.128/bak/login.php? .executemethod(method); // data stream output // method.getResponseBodyAsstream inputStreamInputStreamInputStream = method.getResponseBodyAsstream(); // inputstreamReader(inputstream am)としてバイトストリームオブジェクトを作成します。 bufferedreaderbr = newbufferedReader(newinputStreamReader(inputStream、 "utf-8")); // stringbufferは文字列変数であり、そのオブジェクトを展開および変更して、空のstringbuf fer classbufferstringbuffer = newstringbuffer(); // string stringstr = ""; // string string constant strに文字列ストリームの割り当てwird(sr br.readline()srreadline()! stringbufferstringbuffer.append(str);} // output stringbuffersystem.out.println(stringbuffer.tostring()); // close httpclient connection method.releaseconnection()}}}にstringbufferstringbuffer.append(str);} // stringbufferstringbuffer.append(str);}に割り当てるように変更できます。役職
importjava.io.bufferedreader; importjava.io.ioexception; importjava.io.inputStream; importjava.io.inputStreamReader; importorg.apache.commons.httpclient.methods.postmethod; importorg.apache.commonsh.httpclient BlicstaticVoidMain(String [] args)throwsioException {httpclientclient = newhttpclient(); postmethodmethod = newPostmethod( "http://192.168.111.128/bak/login_post.php"); key = valueNameValuePair [] date = {newnameValuePair( "username"、 "admin")、newnamevaluepair( "password"、 "123457")}; //メソッドはしきい値method.setrequestbody(date); inputStreamInputStream = method.getResponseBodyAsstream(); bufferedreaderbr = newbufferedRead er(newinputStreamReader(inputStream、 "utf-8")); stringbufferstringbuffer = newstringbuffer(); stringstr = ""; while((str = br.readline())!= null){stringbuffer.append(str);} system.out.out.println(stringbuffer.tortring(); method.releaseConnection();}}三つ。
HTTPプロトコルの重要性について詳しく言う必要はありません。従来のJDKに伴うURLConnectionと比較して、HTTPClientは使いやすさと柔軟性が向上します(特定の違いについては後で説明します)。クライアントがHTTP要求を容易にするだけでなく、開発者のテストインターフェイス(HTTPプロトコルに基づく)を促進し、開発効率を向上させ、コードの堅牢性を促進します。したがって、httpclientをマスターすることは非常に重要で義務的です。 HTTPClientを習得した後、HTTPプロトコルの理解はより詳細になると思います。
1。はじめに
HTTPCLIENTは、HTTPプロトコルをサポートする効率的で最新の機能が豊富なクライアントプログラミングツールキットを提供するために、Apache Jakarta Commonの下のサブプロジェクトであり、HTTPプロトコルの最新バージョンと提案をサポートしています。 HTTPClientは、Apache Jakarta、Cactus、Htmlunitの他の2つの有名なオープンソースプロジェクトなど、多くのプロジェクトで使用されており、どちらもHttpClientを使用しています。
2。特性
1。標準ベースの純粋なJava言語。 HTTP1.0およびHTTP1.1を実装しました
2.すべてのHTTPメソッド(GET、POST、PUT、削除、ヘッド、オプション、トレース)は、拡張可能なオブジェクト指向の構造に実装されます。
3。HTTPSプロトコルをサポートします。
4. HTTPプロキシを介して透明な接続を確立します。
5.接続法を使用して、HTTPプロキシを介してトンネルへのHTTPS接続を確立します。
6。BASIC、DIGEST、NTLMV1、NTLMV2、NTLM2セッション、SNPNEGO/KERBEROS認定スキーム。
7。プラグインカスタム認証ソリューション。
8。ポータブルで信頼性の高いソケットファクトリーを使用すると、サードパーティのソリューションを使いやすくなります。
9。ConnectionManagerは、マルチスレッドアプリケーションをサポートしています。接続の最大数の設定をサポートし、ホストあたりの接続数の最大数の設定、期限切れの接続を発見および閉じることもサポートします。
10。セットクーキーのCookieを自動的に処理します。
11。プラグインカスタムクッキーポリシー。
12。リクエストの出力ストリームにより、ストリームの内容がソケットサーバーに直接バッファリングされるのを防ぐことができます。
13。応答の入力ストリームは、ソケットサーバーから対応するコンテンツを直接効果的に読み取ることができます。
14. HTTP1.0およびHTTP1.1でKeepAliveとの永続的な接続を維持します。
15.サーバーから送信された応答コードとヘッダーを直接取得します。
16.接続をタイムアウトする機能を設定します。
17。HTTP1.1応答キャッシュの実験的サポート。
18.ソースコードは、Apacheライセンスに基づいて無料で利用できます。
3。使い方
httpclientを使用してリクエストを送信して応答を受信するのは非常に簡単であり、一般的に次の手順が必要です。
1. HTTPCLIENTオブジェクトを作成します。
2。リクエストメソッドのインスタンスを作成し、リクエストURLを指定します。 GETリクエストを送信する必要がある場合は、HTTPGETオブジェクトを作成します。 POSTリクエストを送信する必要がある場合は、HTTPPOSTオブジェクトを作成します。
3.リクエストパラメーターを送信する必要がある場合は、httpgetとhttppostに共通するsetparams(hetpparams params)メソッドを呼び出すことができます。 httppostオブジェクトの場合、リクエストパラメーターを設定するために、setentity(httpentityエンティティ)メソッドを呼び出すこともできます。
4。HTTPCLIENTオブジェクトの実行(httpurirequestリクエスト)を呼び出してリクエストを送信すると、このメソッドはhttpresponseを返します。
5。HTTPRESPONSEのgetAllHeaders()、Getheaders(String name)およびその他のメソッドを呼び出して、サーバーの応答ヘッダーを取得できます。 HTTPResponseのGetEntity()メソッドを呼び出すと、サーバーの応答コンテンツをラップするHTTPentityオブジェクトを取得できます。プログラムは、このオブジェクトを介してサーバーの応答コンテンツを取得できます。
6.接続をリリースします。実行方法が成功しているかどうかに関係なく、接続はリリースする必要があります。
IV。例
パッケージcom.test; java.io.fileをインポートします。 java.io.fileinputStreamをインポートします。 java.io.ioexceptionをインポートします。 java.io.unsupportedencodingexceptionをインポートします。 java.security.keymanagementexceptionをインポートします。 Java.security.keystoreをインポートします。 java.security.keystoreExceptionをインポートします。 java.security.nosuchalgorithmexceptionをインポートします。 java.security.cert.certificateExceptionをインポートします。 java.util.arraylistをインポートします。 java.util.listをインポートします。 javax.net.ssl.sslcontextをインポートします。 org.apache.http.httpentityをインポートします。 Import org.apache.http.namevaluepair; org.apache.http.parseexceptionをインポートします。 org.apache.http.client.clientprotocolexceptionをインポートします。 org.apache.http.client.entity.urlencodedformentityをインポートします。 org.apache.http.client.methods.closeablehttppresponseをインポートします。 org.apache.http.client.methods.httpgetをインポートします。 org.apache.http.client.methods.httppostをインポートします。 org.apache.http.conn.ssl.sslconnectionSocketFactoryをインポートします。 import org.apache.http.conn.ssl.sslcontexts; org.apache.http.conn.ssl.trustselfsignedstrategyをインポートします。 org.apache.http.entity.contenttypeをインポートします。 org.apache.http.entity.mime.multipartentitybuilderをインポートします。 Import org.apache.http.entity.mime.content.filebody; Import org.apache.http.entity.mime.content.stringbody; import org.apache.http.impl.client.closablehttpclient; org.apache.http.impl.client.httpclientsをインポートします。 org.apache.http.impl.client.httpclientsをインポートします。 org.apache.http.message.basicnamevaluepairをインポートします。 org.apache.http.util.entityutilsをインポートします。 Import org.junit.test;パブリッククラスhttpclienttest {@test public void junittest(){get(); } / ** * httpclient接続ssl * / public void ssl(){closeablehttpclient httpclient = null; try {keystore truststore = keystore.getInstance(keystore.getDefaultType()); fileInputStream entream = new FileInputStream(new File( "d://tomcat.keystore")); try {54。 } catch(cermostexception e){e.printstacktrace(); }最後に{try {enterstream.close(); } catch(例外無視){}} //独自のCAとすべての自己署名証明書sslcontext sslcontext = sslcontexts.custom()。 // TLSV1プロトコルSSLConnectionSocketFactory SSLSF = new SSLConnectionSocketFactory(sslContext、new String [] {"TLSV1"}、null、SSLConnectionSocketSocketFactory.Browsfactory.Browser_compatible_hostname_verifier); httpclient = httpclients.custom()。setsslsocketFactory(sslsf).build(); // httpリクエストを作成(メソッドを取得) system.out.println( "requestの実行" + httpget.getRequestLine()); CLOSEABLEHTTPRESPONSE Response = httppclient.execute(httpget); try {httpentity entity = respons.getEntity(); System.out.println("----------------------------------------"); system.out.println(respons.getStatusline()); if(entity!= null){system.out.println( "応答コンテンツ長:" + entity.getContentLength()); System.out.println(entityutils.toString(entity)); entityutils.consume(entity); }}最後に{response.close(); }} catch(parseexception e){e.printstacktrace(); } catch(ioexception e){e.printstacktrace(); } catch(keymanagementexception e){e.printstacktrace(); } catch(nosuchalgorithmexception e){e.printstacktrace(); } catch(keystoreException e){e.printstacktrace(); }最後に{if(httpclient!= null){try {httpclient.close(); } catch(ioexception e){e.printstacktrace(); }}}}}} / ** *投稿でフォームを送信します(ユーザーログイン要求をシミュレート) closeablehttpclient httpclient = httpclient.createdefault(); // httppost httppost httppost = new httppost( "http:// localhost:8080/mydemo/ajax/serivcej.action"); //パラメーターキューリスト<NameValuePair> forParams = new ArrayList <NameValuePair>(); formparams.add(new BasicNameValuePair( "username"、 "admin")); formparams.add(new BasicNameValuePair( "Password"、 "123456")); urlencodedformentity uefentity; try {uefentity = new urlencodedformentity(formparams、 "utf-8"); httppost.setentity(uefentity); system.out.println( "request" + httppost.geturi()); closeablehttpresponse応答= httpclient.execute(httppost); try {httpentity entity = respons.getEntity(); if(entity!= null){system.out.println( "-----------------------------------"); System.out.println( "Response Content:" + EntityUtils.ToString(Entity、 "UTF-8")); System.out.println( "------------------------------------"); }}最後に{response.close(); }} catch(clientProtoColexception e){e.printstacktrace(); } catch(unsupportedencodingexception e1){e1.printstacktrace(); } catch(ioexception e){e.printstacktrace(); }最後に{//接続を閉じてリソースをリリースします{httpclient.close(); } catch(ioexception e){e.printstacktrace(); }}} / ***ローカルアプリケーションにアクセスして、さまざまなパラメーターに従って異なる結果を返すための投稿リクエストを送信* / public void post(){//デフォルトのhttpclientインスタンスを作成します。 closeablehttpclient httppclient = httpclient.createdefault(); // httppost httppost httppost = new httppost( "http:// localhost:8080/mydemo/ajax/serivcej.action"); //パラメーターキューリスト<NameValuePair> forParams = new ArrayList <NameValuePair>(); forparams.add(new BasicNameValuePair( "type"、 "house")); urlencodedformentity uefentity; try {uefentity = new urlencodedformentity(forparams、 "utf-8"); httppost.setentity(uefentity); system.out.println( "request" + httppost.geturi()); closeablehttpresponse応答= httpclient.execute(httppost); try {httpentity entity = respons.getEntity(); if(entity!= null){system.out.println( "-----------------------------------"); System.out.println( "Response Content:" + EntityUtils.ToString(Entity、 "UTF-8")); System.out.println( "------------------------------------"); }}最後に{response.close(); }} catch(clientProtoColexception e){e.printstacktrace(); } catch(unsupportedencodingexception e1){e1.printstacktrace(); } catch(ioexception e){e.printstacktrace(); }最後に{//接続を閉じてリソースをリリースします{httpclient.close(); } catch(ioexception e){e.printstacktrace(); }}} / *** get requestを送信* / public void get(){closeablehttpclient httpclient = httpclient.createdefault(); try {// httpgetを作成します。 httpget httpget = new httpget( "http://www.baidu.com/"); system.out.println( "request" + httpget.geturi()); // getリクエストを実行します。 CLOSEABLEHTTPRESPONSE Response = httpclient.execute(httpget); try {//応答エンティティhttpentity entity = response.getEntity()を取得します; System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Print responseコンテンツsystem.out.println( "レスポンスコンテンツ長さ:" + entity.getContentLength()); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- } catch(ioexception e){e.printstacktrace(); }最後に{//接続を閉じてリソースをリリースします{httpclient.close(); } catch(ioexception e){e.printstacktrace(); }}} / *** fileをアップロード* / public void upload(){closeablehttpclient httpclient = httpclient.createdefault(); try {httppost httppost = new httppost( "http:// localhost:8080/mydemo/ajax/serivcefile.action"); filebody bin = new filebody(new file( "f://image//sendpix0.jpg")); stringbody comment = new StringBody(「ある種のバイナリファイル」、contentType.text_plain); httpentity reqentity = multipartentitybuilder.create()。addpart( "bin"、bin).addpart( "comment"、comment).build(); httppost.setentity(reqentity); system.out.println( "requestの実行" + httppost.getRequestline()); closeablehttpresponse応答= httpclient.execute(httppost); try {system.out.println( "------------------------------------"); system.out.println(respons.getStatusline()); httpentity resentity = respons.getEntity(); if(resentity!= null){system.out.println( "応答コンテンツ長:" + resentity.getContentLength()); } entityutils.consume(resentity); }最後に{respons.close(); }} catch(clientProtoColexception e){e.printstacktrace(); } catch(ioexception e){e.printstacktrace(); }最後に{try {httpclient.close(); } catch(ioexception e){e.printstacktrace(); }}}}}} </namevaluepair> </namevaluepair> </namevaluepair>httpclientリクエストを送信し、Javaでリクエスト結果を受信するプロセスの上記の簡単な例は、私があなたと共有するすべてのコンテンツです。参照を提供できることを願っています。wulin.comをもっとサポートできることを願っています。