Environment: Java EE 5.0
HTTP request Tool Class
Package Xxx.util;import Java.io.fileoutputstream;import Java.io.ioexception;import java.io.inputstream;import Org.apache.commons.httpclient.httpclient;import Org.apache.commons.httpclient.httpconnectionmanager;import Org.apache.commons.httpclient.httpexception;import Org.apache.commons.httpclient.httpmethod;import Org.apache.commons.httpclient.multithreadedhttpconnectionmanager;import Org.apache.commons.httpclient.namevaluepair;import Org.apache.commons.httpclient.methods.getmethod;import Org.apache.commons.httpclient.methods.postmethod;import Org.apache.commons.httpclient.params.HttpMethodParams; Import Org.apache.commons.httpclient.util.idleconnectiontimeoutthread;import Java.io.file;import Java.util.hashmap;import Java.util.map;import java.util.set;/** * httpclient handling */public class Httpprotocolhandler {/** Connection timeout time, default is 8 seconds */private int defaultconnectiontimeout = 8000; /** response time-out, default is 30 seconds */private int defaultsotimeout = 30000; /** Idle connection Timeout time, default is 60 seconds */private int DEfaultidleconntimeout = 60000; /** defines the maximum number of connections allowed per host, the default is 2*/private int defaultmaxconnperhost = 80; /**httpconnectionmanager the maximum number of connections managed, the default is 20*/private int defaultmaxtotalconn = 100; /** default waits for Httpconnectionmanager to return a connection timeout (only when the maximum number of connections is reached) */private static final long defaulthttpconnectionmanagertimeout = 3 * 1000; /** The HTTP Connection manager, the Connection manager must be thread-safe. */Private Httpconnectionmanager ConnectionManager; private static Httpprotocolhandler Httpprotocolhandler = new Httpprotocolhandler (); /** Factory Method */public static Httpprotocolhandler getinstance () {return httpprotocolhandler; }/** * Private construction method */Private Httpprotocolhandler () {//Create a thread-safe HTTP connection Pool ConnectionManager = new Multithreadedhttpconnectionmanager (); Connectionmanager.getparams (). Setdefaultmaxconnectionsperhost (Defaultmaxconnperhost); Connectionmanager.getparams (). Setmaxtotalconnections (Defaultmaxtotalconn); Connectionmanager.getparams (). sEtconnectiontimeout (defaultconnectiontimeout); Connectionmanager.getparams (). Setsotimeout (Defaultsotimeout); Connectionmanager.getparams (). Setintparameter ("Http.socket.timeout", 30000); Idleconnectiontimeoutthread ICT = new Idleconnectiontimeoutthread (); Ict.addconnectionmanager (ConnectionManager); Ict.setconnectiontimeout (defaultidleconntimeout); Ict.start (); }/** Execute flag */private static Boolean Execflag = true; /** is performing file flags map*/private static map<string, integer> Writingflagmap = new hashmap<string, integer> (); /** recovery times map*/private static map<string, integer> Reconnectmap = new hashmap<string, integer> (); public Boolean Isexecflag () {return execflag;} public void Setexecflag (Boolean execflag) {httpprotocolhandler.execflag = Execflag;} public static map<string, integer> Getwritingflagmap () {return writingflagmap;} public void Setwritingflagmap (map<string, integer>Writingflagmap) {httpprotocolhandler.writingflagmap = Writingflagmap;} /* ******************* The following is the request file *********************** *//** * Request File * @param requesturl * @param savepath * @return */public boolean executegetfile (String requesturl,string savepath) {HttpClient HttpClient = new Ht Tpclient (ConnectionManager); Httpclient.getparams (). Setconnectionmanagertimeout (Defaulthttpconnectionmanagertimeout); FileOutputStream out = null;//System.out.println ("http://" +requesturl); HttpMethod method = new GetMethod ("http://" +requesturl); InputStream in = null; int len =-1; Byte[] B = new byte[1024]; try {Httpclient.executemethod (method); in = Method.getresponsebodyasstream (); if (Method.getstatuscode ()!=200) { SYSTEM.OUT.PRINTLN ("message: http//" +requesturl+ "Access failed, refresh information failed.) "); return false;} out = new FileOutputStream (new File (Savepath)), while ((Len=in.read (b))!=-1) {out.write (b, 0, Len);} Out.flush ();} catch (HttpException e) {e.printstacktrace (); return false;} CAtch (IOException e) {e.printstacktrace (); return false;} finally{try {if (out!=null) {out.close ();}} catch (IOException e) {e.printstacktrace ();} method.releaseconnection ();} return true; }/** * Read file information directly (for small files) * @param requesturl * @return * * * Public String executegetstring (string req Uesturl) {HttpClient HttpClient = new HttpClient (ConnectionManager); Httpclient.getparams (). Setconnectionmanagertimeout (Defaulthttpconnectionmanagertimeout); HttpMethod method = new GetMethod ("http://" +requesturl);//Method.setrequestheader ("Cookie", "jsessionid=" +sessionid ); Method.getparams (). Setcontentcharset ("UTF-8"); String resultstr = ""; try {Httpclient.executemethod (method); resultstr = Method.getresponsebodyasstring (); if (Method.getstatuscode ()!=200 {return null;}} catch (HttpException e) {e.printstacktrace (); return null;} catch (IOException e) {e.printstacktrace (); return null;} finally{method.releaseconnection ();} return resultstr; }/** * Read file information directly (forSmall) * @param requesturl * @return * * * Public String executewsgetstring (string requesturl) {HttpClient h Ttpclient = new HttpClient (ConnectionManager); Httpclient.getparams (). Setconnectionmanagertimeout ( Defaulthttpconnectionmanagertimeout); HttpMethod method = new GetMethod ("http://" + Requesturl); Method.setrequestheader ("Sec-websocket-key", " esajynzeghsnmqbc/btofa== "), Method.setrequestheader (" Upgrade "," WebSocket "); Method.getparams (). Setcontentcharset ("UTF-8"); String resultstr = ""; try {Httpclient.executemethod (method); resultstr = Method.getresponsebodyasstring (); if ( Method.getstatuscode ()! = () {return null;}} catch (HttpException e) {e.printstacktrace (); return null;} catch (IOException e) {e.printstacktrace (); return null;} finally {method.releaseconnection ();} return resultstr; }/* ******************* The following is the post with parameter request *********************** *//** * Post with parameter request * @param requesturl * @param params * @return */public string Executepostreq (string Requesturl,map<string, string> params) {HttpClient HttpClient = new HttpClient (ConnectionManager); Httpclient.getparams (). Setconnectionmanagertimeout (defaulthttpconnectionmanagertimeout);//PostMethod Pmethod = New Postmethod ("http://" +requesturl); Postmethod Pmethod = new Postmethod (Requesturl); namevaluepair[] Nvps = new namevaluepair[params.size ()]; set<string> keys1 = Params.keyset (); int i = 0; for (String name1:keys1) {Namevaluepair p = new Namevaluepair (Name1,params.get (name1)); nvps[i] = P; i++;} pmethod.setrequ Estbody (NVPS); Pmethod.getparams (). Setcontentcharset ("UTF-8"); try {Httpclient.executemethod (Pmethod); if (Pmethod.getstatuscode ( ) {!=200) {return null;} String resultstr = pmethod.getresponsebodyasstring (); return resultstr;} catch (HttpException e) {e.printstacktrace (); return null;} catch (IOException e) {e.printstacktrace (); return null;} finally{pmethod.releaseconnection ();} }/** * Post with parameter request * @param requesturl * @param paramsSTR * @return */Public String executePostReq1 (string requesturl,string paramsstr) {HttpClient HttpClient = New HttpClient (ConnectionManager); Httpclient.getparams (). Setconnectionmanagertimeout (Defaulthttpconnectionmanagertimeout); Postmethod Pmethod = new Postmethod (Requesturl); Pmethod.setrequestbody (PARAMSSTR); Pmethod.getparams (). Setcontentcharset ("UTF-8"); Pmethod.getparams (). Setparameter (Httpmethodparams.http_content_charset, "UTF-8"); Pmethod.addrequestheader ("Content-type", "text/html;charset=utf-8"); try {Httpclient.executemethod (Pmethod); if ( Pmethod.getstatuscode ()!=200) {return null;} String resultstr = pmethod.getresponsebodyasstring (); return resultstr;} catch (HttpException e) {e.printstacktrace (); return null;} catch (IOException e) {e.printstacktrace (); return null;} finally{pmethod.releaseconnection ();} } }
SOAP Request Tool class
Package Xxx.util;import Javax.xml.namespace.qname;import Javax.xml.soap.mimeheaders;import Javax.xml.soap.soapconnectionfactory;import Javax.xml.soap.soapexception;import javax.xml.soap.SOAPConnection; Import Javax.xml.soap.messagefactory;import Javax.xml.soap.soapmessage;import Javax.xml.soap.soappart;import Javax.xml.soap.soapenvelope;import Javax.xml.soap.soapheader;import Javax.xml.soap.soapbody;import Javax.xml.soap.soapbodyelement;import Javax.xml.soap.soapheaderelement;import Javax.xml.soap.Name;import Javax.xml.soap.soapelement;import Javax.xml.ws.dispatch;import Javax.xml.ws.service;import Javax.xml.ws.service.mode;import Javax.xml.ws.soap.soapbinding;import Java.net.URL; Import Java.util.map;import java.util.set;import Javax.activation.datahandler;import Java.io.File;import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.inputstream;import Javax.xml.transform.Source; Import Javax.xml.transform.transformer;import javax.xml.transform.transformerfactory;import jaVax.xml.transform.stream.streamresult;import Org.w3c.dom.node;public class Soapsender {private MessageFactory Msgfactory;private static Soapsender instance = new Soapsender ();p rivate soapsender () {try {//create message factory Msgfactory = MESSAGEF Actory.newinstance (); } catch (SoapException e) {e.printstacktrace (); throw new RuntimeException (e); }}public static Soapsender getinstance () {return instance;} Public Messagefactory Getmessagefactory () {return msgfactory;} /* ******************* The following is to create a soapmessage*********************** *//** * Create a default SoapMessage * @return */public SoapMessage GetMessage () throws SoapException {return msgfactory.createmessage ();} /** * Create SoapMessage * @param params * @return */public soapmessage getMessage (map<string, string> params) throws SOA Pexception, Exception {//Create message object SoapMessage msg = Msgfactory.createmessage ();//Get a Soappart object Soappart Soappart = Message.getsoappart ();//Get envelope SoapEnvelope SoapEnvelope = Soappart.getenvelope ();////Get MessageHead//soapheader SoapHeader = Soapenvelope.getheader ()////Add header element//soapheaderelement headerelement = Soapheader.addheaderelement (Soapenvelope.createname ("Fault", "soapenv", "http://www.xxx.cn"));// Headerelement.addtextnode ("JWS0229043");//***************** Create SOAP message body *****************soapbody soapbody = Soapenvelope.getbody ();//Add message body//name bodyname = soapenvelope.createname ("INFO", "soap-env", "http://www.xxx.cn"); Name bodyname = Soapenvelope.createname ("INFO"); Soapbodyelement bodyelement = soapbody.addbodyelement (bodyname); set<string> keys = Params.keyset (); int i = 0; for (String Name:keys) {Name elename = soapenvelope.createname (name); SOAPElement se = bodyelement.addchildelement (elename);//se.addchildelement ("Servicecode"). Addtextnode ("10000061") ; Se.addtextnode (Params.get (name)); i++; }//*************************************************////Add soap attachment//url url = new URL ("Http://xxx/1.jpg");// DataHandler DataHandler = new DataHandler (URL);//use the Jaf//message.addattachmentpart (messagE.createattachmentpart (DataHandler));//update SOAP message message.savechanges (); return message;} /** * Create SoapMessage * @param headers * @param filepath:soap Format file path * @return */public soapmessage getMessage (mimeheaders he Aders, String FilePath) throws IOException, SoapException {//filepath = Thread.CurrentThread (). Getcontextclassloader () . GetResource ("Soapmessageresp.xml"). GetPath (); InputStream is = new FileInputStream (FilePath); SoapMessage message = Msgfactory.createmessage (headers, is); Is.close (); return message;} /* ******************* The following is the send SOAP request *********************** *//** * Send SOAP request * @param requesturl * @param message */public V OID Send (String requesturl,soapmessage message) throws SoapException, IOException {//create SOAP connection Soapconnectionfactory SCF = Soapconnectionfactory.newinstance (); Soapconnection sc = scf.createconnection ();/* The actual message is sent using the call () method, which receives the message itself and the destination as a parameter and returns the second soapmessage as a response. * The Message object for the call method is the SOAP message sent, and the URL is the inbound port address configured for mule. */url urlendpoint = new URL (Requesturl); Response message SoApmessage response = Sc.call (message, urlendpoint);//*************************************************if (response!) = null) {//Output SOAP messages to console System.out.println ("Receive SOAP Message:"); Response.writeto (System.out);} else {System.err.println ("No response received from partner!");} Close connection Sc.close ();} public void Send1 (String requesturl,soapmessage message) throws SoapException, exception{// Create a SOAP connection soapconnectionfactory SCF = Soapconnectionfactory.newinstance (); Soapconnection sc = scf.createconnection ();//sends a SOAP message to the destination and returns a message URL Urlendpoint = new URL (requesturl); SoapMessage response = Sc.call (message, urlendpoint);//************************************************* Response.setproperty (soapmessage.character_set_encoding, "utf-8");//The SOAP message returned by the print server is for testing System.out.println (" Receive SOAP message: ");//Create a SOAP Messaging Translation object Transformerfactory transformerfactory = Transformerfactory.newinstance (); Transformer Transformer = Transformerfactory.newtransformer ();//Extract message content source sourcecontent = Response.getsoappart (). getcontent ();//Set the output for the Transformationstreamresult result = new Streamresult (System.out); Transformer.transform (sourcecontent, result);//* * * Close connection sc.close ();//********************************************** /* Impersonate client A, exception handling test */soapbody Ycbody = Response.getsoapbody (); Node Ycresp = Ycbody.getfirstchild (); System.out.print ("ReturnValue:" +ycresp.gettextcontent ());} /** * Send SOAP request public void Send1 (String requesturl,soapmessage request) {//define servicename corresponding QName, the first parameter is corresponding namespace QNa Me serviceName = new QName ("http://xxx.com/", "Soapmessageservice"); Define portname corresponding QName QName portname = new QName ("http://xxx.com/", "Soapmessageport"); Use ServiceName to create a service object that cannot interact directly with the WebService object Service service = Service.create (serviceName);//// Specifies the location of the WSDL file//url wsdl = new URL ("http://localhost:8080/test/jaxws/services/SOAPMessage?wsdl");//service Service = Service.creATE (WSDL, serviceName); Create a port and specify the address of the webservice, and we can create the dispatch after the specified address. Service.addport (PortName, soapbinding.soap11http_binding, Requesturl); Create a Dispatch object dispatch<soapmessage> Dispatch = Service.createdispatch (PortName, Soapmessage.class, Mode.message); Call Dispatch's Invoke method, send a SoapMessage request, and return a soapmessage response. SoapMessage response = Dispatch.invoke (request); SYSTEM.OUT.PRINTLN ("service side returns as follows:"); try {response.writeto (system.out);} catch (Exception e) {}} */}
Test method
public static void Main (string[] args) throws SoapException, Exception {map<string, string> params = new hashmap< String, string> ();p arams.put ("A", "1"); String string= "http://xxx/xxx";/** ************* The following is a SOAP request ***************** */soapsender sender = Soapsender.getinstance (); SoapMessage message = Sender.getmessage ();//soapmessage message = Sender.getmessage (params);//soapmessage message = Sender.getmessage (NULL, "D:\\soapmessageresp.xml"); Message.writeto (System.out); Sender.send (string,message);/** * The following is an HTTP request ***************** */// httpprotocolhandler Httpprotocolhandler = Httpprotocolhandler.getinstance (); System.out.println (Httpprotocolhandler.executepostreq (string, params)); System.out.println (string);//system.out.println (Httpprotocolhandler.executegetstring (String));}
Request (HTTP, SAOP)