하나.
1. 후 요청 및 요청을 포함하여 httprequestutils 도구 클래스 작성
패키지 com.brainlong.framework.util.httpclient; import net.sf.json.jsonobject; import org.apache.commons.httpclient.httpstatus; import org.apache.httpresponse; import org.apache.http.client.methods.httpget; import org.apache.http.client.method.htposts; 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; import java.io.ioexception; import java.net.urldecoder; 공개 클래스 httprequestutils {private static 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 결과를 반환 할 필요가 없습니다* @return* /public static jsonobject httppost (String URL, JsonObject jsonParam, boolean noneedResponse) {// post reture Reture Reture Reture Reture httpclient httpclient. defaulthttpclient (); jsonobject jsonresult = null; httppost method = new httppost (URL); try {if (null! = jsonparam) {// 중국식 문제 해결 엄격한 엔티티를 해결하십시오. entity.setContentEncoding ( "UTF-8"); Entity.SetContentType ( "Application/JSON"); 메소드 .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 (예외 e) {logger.error ( "사후 요청 제출 실패 :" + url, e); }}} catch (ioexception e) {logger.error ( "Post Request Submission 실패 :" + url, e); } return JSONRESULT; } /*** 요청 받기 요청* @param url path* @return* /public static jsonobject httpget (문자열 URL) {// 요청을 반환하기 jsonobject jsonresult = null; try {defaulthttpclient client = new defaulthttpclient (); // 요청 받기 요청 httpget request = new httpget (url); httpresponse response = client.execute (요청); / ** 요청이 성공적으로 전송되었고 응답을 받았습니다 **/ if (response.getStatusline (). getStatusCode () == httpstatus.sc_ok) {/ ** 서버에서 반환 한 JSON 문자열 데이터를 읽습니다 **/ StringStresult = entityUtils.toString (response.getEntity ()); / ** JSON 문자열을 JSON 개체로 변환 **/ jsonResult = jsonObject.fromObject (strresult); url = urldecoder.decode (url, "utf-8"); } else {logger.error ( "요청 제출 실패 :" + url); }} catch (ioexception e) {logger.error ( "요청 제출 실패 :" + url, e); } return JSONRESULT; }}2. HTTP 요청을 보내려면 비즈니스 코드를 작성하십시오
3. MVC 구성 파일 설정 컨트롤러 스캔 디렉토리
<!-자동 스캔 및 전용 스캔 @controller--> <context : component-scan base-package = "com.wiselong.multchannel"use-default-filters = "false"> <context : include-filter type = "Annotation"expression = "org.springframework.steretype.controller" /> < /context : component-scan>.
4. HTTP 요청을받습니다
사후 요청을받습니다
@controller@requestmapping (value = "/api/platform/exception/exception/exception")) publicclassexceptioninfocontroller {// @autowiredprivateExceptionInfoBizexceptionInfobiz;/*** 예외 정보 요청*@paramrequestbody 요청 메시지 컨텐츠*@p aramrequest 요청 메시지 header*@returnJsonObject*/@requestMapping (value = "/create", method = requestMethod.post) publicModelandViewCreateExceptionInfo (@requestBodyStringRequestBody, httpservletRequestRequest) {jsonObjectJsonObject ct = jsonobject.fromobject (requestody); comexceptionInfocomeXceptionInfo = newcomeXceptionInfo (); comexceptionInfo.setProjectName (jsonObject. getString ( "projectName")); comeXceptionInfo.setTagName (jsonObject.getString ( "projectName")); comeXceptionInfo.setTagName (jsonObject.getStrs ing ( "tagname"); exceptioninfobiz.insert (comexceptionInfo); // 요청 결과를 반환하면 jsonobjectresult = newjsonObject (); result.put ( "success", "true"); returnNewModelandView ( ", responseUtilShelper.jsuccess (result.toString ());}}}}받기 요청을받습니다
@controller@requestmapping (value = "/api/platform/messagecenter/message/sms")) publicclasssmscontroller {@autowizedsmsssendbizsmssendbiz;/*** SMS 보내기 테이블*@paramrequest 요청 메시지에 레코드를 보내고 레코드를 삽입하십시오. 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 (요청, 전화, 전화 e "); StringContent = requestItils.getStringValue (요청,"content "); smssendBiz.insertttmsququ (전화, 내용); 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 (); // get 메소드를 URL 서버와 상호 작용하기 위해 get 메소드를 사용하십시오 // httpmethodmethod = newgetMethod ( "http://192.168.111.128/bak/regist.php? d = 1234567 & re_password = 1234567 & username = admin & nickname = admin "); httpmethodmethod = newgetMethod ("http://192.168.1111.128/bak/login.php?username= "); .ExecutEMETHOD (method); // data Stream output // method.getResponseBodyAsStream inputStreamInputStreamInputStream = method.getResponseBodyAsStream (); inputStreamReader (inputStream AM)로 바이트 스트림 객체를 만듭니다. 바이트 스트림은 문자 스트림 버퍼와 함께 특성 개체로 캡슐화됩니다. bufferedReaderBr = NewbufferedReader (newInputStreamReader (inputStream, "utf-8")); // StringBuffer는 문자열 변수이며, 객체를 확장하고 수정하여 빈 StringBuf fer class 객체 StringBufferstringBuffer = newStringBuffer = // string constant stringstr = ""; // str string string에 문자열 스트림을 할당하는 str str str str str str str를 동일하게하지 않습니다. (str = br.readline ())! StringBufferstringBuffer.append (str);} // output StringBufferSystem.out.println (StringBuffer.toString ()); // httpclient connection methys.releaseconnection ()}}에 str data를 stringbufferstringbuffer.append (str);}에 할당하기 위해 객체를 확대하고 수정할 수 있습니다.우편
importjava.io.bufferedReader; importJava.io.ioException; importJava.io.inputStream; importJava.io.inputStreamReader; importorg.apache.commons.httpclient.methods.postmethod; importorg.apache.commons.httpclient blicstaticVoidMain (Strows [] args) ThrowsioException {httpclientClient = newhttpclient (); postMethodMethod = newPostMethod ( "http://192.168.111.128/bak/login_post.php"); key = valuenamevaluepair [] date = {newnamevaluepair ( "username", "admin"), newnamevaluepair ( "password", "123457"}}}; // 메소드는 양식 임계 값을 사용합니다. 양식 client. // methove); inputStreamInputStream = method.getResponseBodyAsStream (); bufferedReaderBr = newbufferedRead er (newInputStreamReader (inputStream, "utf-8"); StringBufferstringBuffer = NewStringBuffer (); stringstr = "; method.releaseConnection ();}}삼.
HTTP 프로토콜의 중요성에 대해 더 말할 필요는 없습니다. 전통적인 JDK와 함께 제공되는 urlconnection과 비교할 때, HTTPClient는 사용 편의성과 유연성을 증가시킵니다 (특정 차이는 나중에 논의 될 것입니다). 클라이언트가 HTTP 요청을보다 쉽게 보낼 수있을뿐만 아니라 개발자의 테스트 인터페이스 (HTTP 프로토콜 기반)를 용이하게하여 개발 효율성을 향상시키고 코드 견고성을 용이하게합니다. 따라서 httpclient를 마스터하는 것은 매우 중요하고 강제입니다. httpclient를 마스터 한 후, 나는 HTTP 프로토콜에 대한 나의 이해가 더 깊이있을 것이라고 생각합니다.
1. 소개
httpclient는 HTTP 프로토콜을 지원하는 효율적이고 최신 기능이 풍부한 클라이언트 프로그래밍 툴킷을 제공하기 위해 Apache Jakarta Common의 하위 프로젝트이며 HTTP 프로토콜의 최신 버전 및 제안을 지원합니다. httpclient는 Apache Jakarta, Cactus 및 Htmlunit의 다른 잘 알려진 오픈 소스 프로젝트와 같은 많은 프로젝트에서 httpclient를 사용합니다.
2. 특성
1. 표준 기반의 순수한 자바 언어. HTTP1.0 및 HTTP1.1 구현
2. 모든 HTTP 방법 (Get, Post, Put, Delete, Head, Options 및 Trace)은 확장 가능한 객체 지향 구조로 구현됩니다.
3. HTTPS 프로토콜 지원.
4. HTTP 프록시를 통해 투명한 연결을 설정하십시오.
5. 연결 방법을 사용하여 HTTP 프록시를 통해 터널에 HTTPS 연결을 설정하십시오.
6. BASIC, DIGEST, NTLMV1, NTLMV2, NTLM2 세션, SNPNEGO/KERBEROS 인증 체계.
7. 플러그인 사용자 정의 인증 솔루션.
8. 휴대용 및 안정적인 소켓 공장을 사용하면 타사 솔루션을보다 쉽게 사용할 수 있습니다.
9. Connection Manager는 다중 스레드 응용 프로그램을 지원합니다. 최대 연결 수 설정을 지원하며 호스트 당 최대 연결 수를 설정하고 만료 된 연결을 발견하고 폐쇄하는 것이 지원됩니다.
10. 세트 쿠키의 쿠키를 자동으로 처리합니다.
11. 플러그인 사용자 정의 쿠키 정책.
12. 요청의 출력 스트림은 스트림의 내용이 소켓 서버에 직접 버퍼링되는 것을 방지 할 수 있습니다.
13. 입력 응답 스트림은 소켓 서버에서 직접 해당 콘텐츠를 효과적으로 읽을 수 있습니다.
14.
15. 서버에서 보낸 응답 코드와 헤더를 직접 얻습니다.
16. 연결 시간을 설정하는 기능을 설정하십시오.
17. HTTP1.1 응답 캐싱에 대한 실험 지원.
18. 소스 코드는 Apache 라이센스를 기반으로 무료로 사용할 수 있습니다.
3. 사용 방법
httpclient를 사용하여 요청을 보내고 응답을받는 것은 매우 간단하며 일반적으로 다음 단계가 필요합니다.
1. HttpClient 객체를 만듭니다.
2. 요청 메소드의 인스턴스를 작성하고 요청 URL을 지정하십시오. GET 요청을 보내야하는 경우 httpget 객체를 작성하십시오. 게시물 요청을 보내야하는 경우 httppost 객체를 만듭니다.
3. 요청 매개 변수를 보내야하는 경우 httpget 및 httppost에 공통된 setparams (hetpparams params) 메소드를 호출하여 요청 매개 변수를 추가 할 수 있습니다. httppost 객체의 경우 setentity (httpentity entity) 메소드를 호출하여 요청 매개 변수를 설정할 수도 있습니다.
4. httpclient 객체의 실행 (httpurirequest 요청)을 호출하여 요청을 보내고이 메소드는 httpresponse를 반환합니다.
5. HTTPresponse의 getAllHeaders (), getheaders (문자열 이름) 및 기타 메소드 호출은 서버의 응답 헤더를 얻을 수 있습니다. httpresponse의 getentity () 메소드를 호출하면 서버의 응답 내용을 감싸는 httpentity 객체를 얻을 수 있습니다. 프로그램은이 객체를 통해 서버의 응답 내용을 얻을 수 있습니다.
6. 연결을 해제하십시오. 실행 방법이 성공 여부에 관계없이 연결을 해제해야합니다.
IV. 예
패키지 com.test; import java.io.file; import java.io.fileInputStream; import java.io.ioexception; java.io.unsupportedencodingException 가져 오기; Java.Security.KeyManagementException 가져 오기; java.security.keystore 가져 오기; java.security.keystoreException 가져 오기; java.security.nosuchalgorithmexception import; java.security.cert.certificateException 가져 오기; java.util.arraylist 가져 오기; Java.util.list 가져 오기; import javax.net.ssl.sslcontext; import org.apache.http.httpentity; import org.apache.http.namevaluepair; import org.apache.http.parseexception; import org.apache.http.client.clientprotocolexception; import org.apache.http.client.entity.urlencodedformentity; import org.apache.http.client.methods.closeablehttpresponse; import org.apache.http.client.methods.httpget; import org.apache.http.client.methods.httppost; import org.apache.http.conn.ssl.sslconnectionsocketfactory; import org.apache.http.conn.ssl.sslcontexts; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.contentType; import 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.closeablehttpclient; import org.apache.http.impl.client.httpclients; import org.apache.http.impl.client.httpclients; import org.apache.http.message.basicnamevaluepair; import org.apache.http.util.entityutils; import org.junit.test; 공개 클래스 httpclientTest {@test public void junittest () {get (); } / ** * httpclient Connection ssl * / public void ssl () {closeblehttpclient httpclient = null; {keystore trustStore = keystore.getInstance (keystore.getDefaultType ()); fileInputStream instream = new FileInputStream (새 파일 ( "d : //tomcat.keystore"); {54. // KeyStore를로드 : //tomcat.keystore truststore.load (Instream, "123456".tochararray ()); } catch (reateralexception e) {e.printstacktrace (); } 마침내 {try {enterstream.close (); } catch (예외 무시) {}} // 자신의 CA 및 모든 자체 서명 된 인증서 SSLCONTEXT SSLCONTEXT = SSLCONTEXTS.CUSTOM (). LOADTRUSTMATERIAL (TrustStore, New TrustSelfSignedStrategy ()). 빌드 (); // TLSV1 프로토콜 만 사용 SSLConnectionSocketFactory SSLSF = New SSLConnectionSocketFactory (SSLContext, New String [] { "TLSV1"}, NULL, SSLCONNECTIONSOCKFACTORY.BROWSER_COMPATIBE_HOSTNAME_VERIFIER); httpclient = httpclients.custom (). setsslsocketfactory (sslsf) .build (); // http 요청 (get 메서드) httpget httpget = new httpget ( "https : // localhost : 8443/mydemo/ajax/serivcej.action"); system.out.println ( "실행 요청" + httpget.getRequestline ()); CloseableHttPresponse 응답 = httppclient.execute (httpget); {httpentity entity = response.getentity (); System.out.println ( "-------------------------------------------------------- System.out.println (response.getStatusline ()); if (entity! = null) {system.out.println ( "응답 내용 길이 :" + entity.getContentLength ()); System.out.println (entityutil.tostring (entity)); entityutils.consume (엔티티); }} 마침내 {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 (); }}}}}} / ** * 포스트에서 양식을 제출합니다 (사용자 로그인 요청 시뮬레이션) * / public void postform () {// 기본 httpclient 인스턴스를 만듭니다. CloseblayHttPclient httpclient = httpclients.createdefault (); // httppost 만들기 httppost httppost = new httppost ( "http : // localhost : 8080/mydemo/ajax/serivcej.action"); // 매개 변수 작성 큐 큐어 목록 작성 <NamesValuePair> forparams = new ArrayList <NamesValuePair> (); formparams.add (New BasicNameValuePair ( "사용자 이름", "admin")); formparams.add (New BasicNameValuePair ( "password", "123456")); urlencodedformentity uefentity; try {uefentity = new urlencodedformentity (formparams, "utf-8"); httppost.setentity (uefentity); System.out.println ( "실행 요청" + httppost.geturi ()); CloseableHttPresponse 응답 = httpclient.execute (httppost); {httpentity entity = response.getentity (); if (entity! = null) {System.out.println ( "----------------------------------------------------------------------------- System.out.println ( "응답 내용 :" + entityutils.toString (엔티티, "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 ()에 따라 로컬 응용 프로그램에 액세스하고 다른 결과를 반환하려는 게시물 요청을 보내십시오. Closeblehttpclient httppclient = httpclients.createdefault (); // httppost 만들기 httppost httppost = new httppost ( "http : // localhost : 8080/mydemo/ajax/serivcej.action"); // 매개 변수 작성 큐 큐어 목록 작성 <NamesValuePair> forparams = new ArrayList <NamesValuePair> (); forparams.add (New BasicNameValuePair ( "type", "house")); urlencodedformentity uefentity; try {uefentity = new urlencodedformentity (forparams, "utf-8"); httppost.setentity (uefentity); System.out.println ( "실행 요청" + httppost.geturi ()); CloseableHttPresponse 응답 = httpclient.execute (httppost); {httpentity entity = response.getentity (); if (entity! = null) {System.out.println ( "----------------------------------------------------------------------------- System.out.println ( "응답 내용 :" + entityutils.toString (엔티티, "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 요청 보내기* / public void get () {closeablehttpclient httpclient = httpclients.createdefault (); {// httpget을 만듭니다. httpget httpget = new httpget ( "http://www.baidu.com/"); System.out.println ( "실행 요청" + httpget.geturi ()); // GET 요청을 실행합니다. CloseableHttPresponse 응답 = httpclient.execute (httpget); 시도 {// 응답 엔티티 httpentity entity = response.getentity (); System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Print response Content Length.out.println ( "응답 컨텐츠 길이 :" + entity.getContentLength ()); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- } catch (ioexception e) {e.printstacktrace (); } 마침내 {// 연결을 닫고 리소스를 릴리스합니다. {httpclient.close (); } catch (ioexception e) {e.printstacktrace (); }}} / *** 파일 업로드* / public void upload () {closeablehttpclient httpclient = httpclients.createdefault (); {httppost httppost = new httppost ( "http : // localhost : 8080/mydemo/ajax/serivcefile.action"); filebody bin = new FileBody (새 파일 ( "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 ( "실행 요청" + httppost.getRequestline ()); CloseableHttPresponse 응답 = httpclient.execute (httppost); {System.out.println ( "------------------------------------------------------------------------------------------------------ System.out.println (response.getStatusline ()); httpentity fenentity = response.getentity (); if (enterentity! = null) {System.out.println ( "응답 내용 길이 :" + enentity.getContentLength ()); } entityutils.consume (분개); } 마침내 {response.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을 더 지원할 수 있기를 바랍니다.