Java cross-domain request operations--encapsulating classes

Source: Internet
Author: User
Tags readline stringbuffer

Cross-domain requests, as the name suggests, are resources in one site to access resources on another different domain name site. A resource can be a request, or an action or a data stream, etc.

Note: 2 packages are used in the Httpclient.jar package, please go to the Internet search download.

(i) encapsulation Class A

/** * cross-Domain Request action class *@authorYangzhifeng *@version1.0 *@created2012-8-10 10:56:15 *publicclass Httpclientutil {/** * cross-domain request and receive data returned * parameter description: URL: Cross-domain requested address params: parameters to pass, format: parameter 1=aaa& parameter b=bbb& parameter C=CCC *@returnString *@throwsIOException *@throwsHttpException * PublicStaticString transboundaryrequest (string url, string params)throwsHttpException, IOException {//request method String response=NewString (); HttpClient client =NewHttpClient (); Solve garbled problem client.getparams (). Setparameter (Httpmethodparams.http_content_charset, "UTF-8"); Postmethod method =NewPostmethod (objectutils.tostring (URL)); string[] Paramlist = Params.split ("&"); for(inti = 0; i < paramlist.length; i++) {string[] param = paramlist[i].split ("=");if(param[0]!= "") {if(param.length>1) {Method.addparameter (param[0],objectutils.tostring (param[1]));}Else{Method.addparameter (param[0], "");} } client.executemethod (method); Response = method.getresponsebodyasstring (); returnResponse }

}

(ii) package class two

package com.gzedu.util; import Java.io.BufferedReader; import java.io.IOException; import Java.io.InputStream; import Java.io.InputStreamReader; import Java.util.Iterator; import Java.util.Map; import java.util.Map.Entry; import Org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import Org.apache.commons.httpclient.methods.GetMethod; import Org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import Org.apache.commons.httpclient.params.HttpMethodParams;/** * Interface Cast get/post request *@authorXiaoming * * * * *publicclass httpclientutils { PrivateStaticInteger SC_OK = 200; /** * Get Way *@paramURL *@paramparams *@paramTimeout *@return* * @SuppressWarnings ("unchecked") PublicStaticString dohttpget (string url, Map params,intTimeout, string encode) {string responsemsg = ""; HttpClient httpclient =NewHttpClient (); Httpclient.getparams (). Setcontentcharset (encode); StringBuffer SB =NewStringBuffer ();if(Params!=NULL&&!params.isempty ()) {Iterator iterator = Params.entryset (). iterator (); while(Iterator.hasnext ()) {Entry Entry = (Entry) iterator.next (); Sb.append (Entry.getkey (). ToString () + "=" + Entry.getvalue (). ToString () + & ); url = url + "?" + sb.substring (0, Sb.length ()-1); } GetMethod GetMethod =NewGetMethod (URL); Getmethod.getparams (). Setparameter (Httpmethodparams.retry_handler,NewDefaulthttpmethodretryhandler ());Try{Httpclient.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (timeout);intnum = Httpclient.executemethod (GetMethod);if(Num ==SC_OK) {InputStream is = Getmethod.getresponsebodyasstream (); BufferedReader br =NewBufferedReader (NewInputStreamReader (IS)); String TEMPBF; StringBuffer html=NewStringBuffer (1000); while((Tempbf=br.readline ())!=NULL) {html.append (TEMPBF);} responsemsg = Html.tostring (); } }Catch(Exception e) {E.printstacktrace ();}finally{getmethod.releaseconnection ();} returnresponsemsg; /** * Post Method *@paramURL *@paramparams *@paramTimeout *@return* * @SuppressWarnings ("unchecked") PublicStaticString dohttppost (string url, Map params,intTimeout, string encode) {string responsemsg = ""; HttpClient httpclient =NewHttpClient (); Httpclient.getparams (). Setcontentcharset (encode); Postmethod Postmethod =NewPostmethod (URL);if(Params!=NULL&&!params.isempty ()) {Iterator iterator = Params.entryset (). iterator (); while(Iterator.hasnext ()) {Entry Entry = (Entry) iterator.next (); Postmethod.addparameter (Entry.getkey (). ToString (), Entry. GetValue (). ToString ()); } }Try{Httpclient.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (timeout);intnum = Httpclient.executemethod (Postmethod);if(Num ==SC_OK) {InputStream is = Postmethod.getresponsebodyasstream (); BufferedReader br =NewBufferedReader (NewInputStreamReader (IS)); String TEMPBF; StringBuffer html=NewStringBuffer (1000); while((Tempbf=br.readline ())!=NULL) {html.append (TEMPBF);} responsemsg = Html.tostring (); } }Catch(Exception e) {E.printstacktrace ();}finally{postmethod.releaseconnection ();} returnresponsemsg; /*** * Send XML file *@paramURL *@paramXML *@paramTimeout *@paramEncode *@return*/ PublicStaticString dohttppostxml (string url, String xmlstring,intTimeout, string encode) {string responsestring = ""; HttpClient httpclient =NewHttpClient (); Httpclient.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (timeout); Postmethod Postmethod =NewPostmethod (URL);Try{Postmethod.setrequestheader ("Content-type", "text/xml,charset=" +encode); Postmethod.setrequestentity (NewStringrequestentity (xmlstring, "Text/xml", encode));intStatusCode = Httpclient.executemethod (Postmethod);if(StatusCode ==SC_OK) {InputStream is = Postmethod.getresponsebodyasstream (); BufferedReader br =NewBufferedReader (NewInputStreamReader (IS)); String TEMPBF; StringBuffer html=NewStringBuffer (1000); while((Tempbf=br.readline ())!=NULL) {html.append (TEMPBF);} responsestring = Html.tostring (); } }Catch(HttpException e) {E.printstacktrace ();}Catch(IOException e) {E.printstacktrace ();} returnresponsestring; } }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.