server sends XML request Java code sample

Source: Internet
Author: User
Tags throw exception

/** *  */ PackageCom.autoyol.pay.cmb.core;ImportJava.io.ByteArrayOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.net.HttpURLConnection;Importjava.net.SocketTimeoutException;ImportJava.net.URL;Importjava.security.KeyManagementException;Importjava.security.KeyStoreException;Importjava.security.NoSuchAlgorithmException;Importjava.security.UnrecoverableKeyException;Importorg.apache.http.HttpEntity;ImportOrg.apache.http.HttpResponse;ImportOrg.apache.http.HttpStatus;ImportOrg.apache.http.client.config.RequestConfig;ImportOrg.apache.http.client.methods.HttpPost;Importorg.apache.http.conn.ConnectTimeoutException;Importorg.apache.http.conn.ConnectionPoolTimeoutException;Importorg.apache.http.entity.StringEntity;Importorg.apache.http.impl.client.CloseableHttpClient;Importorg.apache.http.impl.client.HttpClients;Importorg.apache.http.util.EntityUtils;/** * @authorXXX * @function * @date March 23, 2016 *@version */ Public classSender {/**     *      * @paramURL *@paramPostdataxml *@return     * @throwsException*/     Public StaticString sendrq (string url, string postdataxml)throwsexception{String Result=NULL; OutputStream out=NULL; InputStream is=NULL; Bytearrayoutputstream Bos=NULL; HttpURLConnection URLC=NULL; Try{URL URLACC=Newurl (URL); URLC=(HttpURLConnection) urlacc.openconnection (); Urlc.setconnecttimeout (100000); Urlc.setreadtimeout (100000); Urlc.setdooutput (true); Urlc.setdoinput (true); Urlc.setusecaches (false); Urlc.setinstancefollowredirects (false);//whether redirection is handled automaticallyUrlc.setrequestmethod ("POST"); out=Urlc.getoutputstream ();            Out.write (Postdataxml.getbytes ());            Out.flush ();                        Out.close (); is=Urlc.getinputstream (); if(is!=NULL) {BOS=NewBytearrayoutputstream (); byte[] Receivebuffer =New byte[2048]; intReadbytessize =Is.read (Receivebuffer);  while(Readbytessize! =-1) {bos.write (Receivebuffer,0, readbytessize); Readbytessize=Is.read (Receivebuffer); } result=NewString (Bos.tobytearray (), "UTF-8");//respxml= Parseutil.parsexml (reqdata,transinfo); //XML parsingSystem.out.println ("result=" +result); }        } Catch(Exception e) {//System.out.println ("Send TR1 failed");e.printstacktrace ();//logger.error ("sendTR1 Exception2:", e); //sendTR1 Exception2:java.net.NoRouteToHostException: No route to host//throw E; //The exception is thrown again to resolve sendTR1 Exception2:java.net.ConnectException: Connection timed out network exception condition. 160201 huangjing}finally{            if(Bos! =NULL) {bos.close (); }            if(Is! =NULL){                Try{is.close (); } Catch(IOException e) {e.printstacktrace (); }            }            if(Out! =NULL){                Try{out.close (); } Catch(IOException e) {e.printstacktrace (); }            }            if(URLC! =NULL) {urlc.disconnect (); }        }        returnresult; }            /**     *      * @paramURL *@paramPostdataxml *@return     * @throwsIOException *@throwskeystoreexception *@throwsunrecoverablekeyexception *@throwsnosuchalgorithmexception *@throwskeymanagementexception*/     Public StaticString sendpost (string url, string postdataxml)throwsIOException, Keystoreexception, Unrecoverablekeyexception, NoSuchAlgorithmException, KeyManagementException { String result=NULL; HttpPost HttpPost=Newhttppost (URL); System.out.println ("Api,post Past data is:" +postdataxml); //must indicate that the UTF-8 encoding is used, otherwise the Chinese cannot be successfully identified to the API server XMLStringentity postentity =NewStringentity (Postdataxml, "UTF-8"); Httppost.addheader ("Content-type", "Text/xml");        Httppost.setentity (postentity); //set the configuration of the requestorCloseablehttpclient httpClient =Httpclients.custom (). build ();//closeablehttpclient httpClient = httpclientbuilder.create (). build (); //Initialize requestconfig based on the default timeout limitRequestconfig requestconfig = Requestconfig.custom (). SetSocketTimeout (10000). Setconnecttimeout (30000). build ();        Httppost.setconfig (Requestconfig); System.out.println ("Executing request:" +httppost.getrequestline ()); Try{HttpResponse response=Httpclient.execute (HttpPost); intHttpStatusCode =response.getstatusline (). Getstatuscode (); if(HttpStatusCode = =HTTPSTATUS.SC_OK) {httpentity entity=response.getentity (); Result= Entityutils.tostring (Entity, "UTF-8"); System.out.println ("Result=" +result); }Else{System.err.println ("Error,httpstatuscode is ' {" +httpstatuscode+ "} '"); }        } Catch(connectionpooltimeoutexception e) {System.err.println ("HTTP Get throw connectionpooltimeoutexception (wait Time Out)"); } Catch(connecttimeoutexception e) {System.err.println ("HTTP Get throw connecttimeoutexception"); } Catch(sockettimeoutexception e) {System.err.println ("HTTP Get throw sockettimeoutexception"); } Catch(Exception e) {System.err.println ("HTTP Get throw Exception"); } finally{httppost.abort (); }        returnresult; }    }

server sends XML request Java code sample

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.