Java:http request (Code explanation)

Source: Internet
Author: User
Tags finally block soap readline wsdl

java native API

public class HttpRequest {/** * a request to send a GET method to a specified URL * * @param URL * Send the requested URL * @param     param * Request parameters, request parameters should be in the form of name1=value1&name2=value2.        * The response result of the remote resource represented by the @return URL */public static string Sendget (string URL, string param) {string result = "";        BufferedReader in = null;            try {String urlnamestring = URL + "?" + param;            URL realurl = new URL (urlnamestring);            The connection between open and URL urlconnection connection = Realurl.openconnection ();            Set the generic request attribute Connection.setrequestproperty ("accept", "*/*");            Connection.setrequestproperty ("Connection", "keep-alive"); Connection.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 6.0; Windows NT 5.1;            SV1) ");            Establish the actual connection connection.connect (); Get all response header fields Map<string, list<string>> Map = Connection.getheaderfielDS (); Traverse all response header fields for (String Key:map.keySet ()) {System.out.println (key + "--->" + map.get (key            ));                    }//define BufferedReader input stream to read the response of the URL in = new BufferedReader (New InputStreamReader (            Connection.getinputstream ()));            String Line;            while (line = In.readline ()) = null) {result + = line; }} catch (Exception e) {System.out.println ("Send GET request exception!)            "+ e);        E.printstacktrace (); }//Use finally block to close the input stream finally {try {if (in! = null) {In.clos                E ();            }} catch (Exception E2) {e2.printstacktrace ();    }} return result;            /** * Request to send a POST method to the specified URL * * @param URL * Send the requested URL * @param param *     Request parameters, request parameters should be in the form of name1=value1&name2=value2. * Represented by @returnResponse result of remote resource */public static string Sendpost (string url, string param) {printwriter out = null;        BufferedReader in = null;        String result = "";            try {URL realurl = new URL (URL);            The connection between open and URL URLConnection conn = realurl.openconnection ();            Set the generic request attribute Conn.setrequestproperty ("accept", "*/*");            Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 6.0; Windows NT 5.1;            SV1) ");            The Send POST request must be set to the following two lines conn.setdooutput (true);            Conn.setdoinput (TRUE);            Gets the output stream corresponding to the URLConnection object out = new PrintWriter (Conn.getoutputstream ());            Send request parameter out.print (param);            Flush output Stream Buffer Out.flush (); Defines the BufferedReader input stream to read the response of the URL in = new BufferedReader (New InputStreamReader (CONN.GETINPUtstream ()));            String Line;            while (line = In.readline ()) = null) {result + = line; }} catch (Exception e) {System.out.println ("send POST request exception!            "+e);        E.printstacktrace (); }//Use finally block to close the output stream, input stream finally{try{if (out!=null) {Out.close                ();                } if (In!=null) {in.close ();            }} catch (IOException ex) {ex.printstacktrace ();    }} return result; }/** * @param args */public static void main (string[] args) {//TODO auto-generated method Stu b//Send GET request//String S=httprequest.sendget ("Http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMob        Ilecodeinfo "," mobilecode=13069208531&userid= ");//System.out.println (s); Send a POST request String sr=httprequest.sendpost ("http:Ws.webxml.com.cn/webservices/mobilecodews.asmx/getmobilecodeinfo "," mobilecode=13069208531&userid= ");    System.out.println (SR); }}

The

HttpClient requires a jar package:

public class Httputils {private final static Logger Logger = Logger.getlogger (Httputils.class);     Private final static String Operater_name = "http Operation" ";     Private final static int SUCCESS = 200;     Private final static String UTF8 = "UTF-8";     Private HttpClient client;     Private final String Respondtypexml = "application/x-www-form-urlencoded";     Private final String Respondtypejson = "Application/json;charse=utf-8";     private static Httputils instance = new Httputils ();         Private Httputils () {Httpconnectionmanager Httpconnectionmanager = new Multithreadedhttpconnectionmanager ();         Httpconnectionmanagerparams params = Httpconnectionmanager.getparams ();         Params.setconnectiontimeout (5000);         Params.setsotimeout (20000);         Params.setdefaultmaxconnectionsperhost (1000);         Params.setmaxtotalconnections (1000);         Client = new HttpClient (Httpconnectionmanager);         Client.getparams (). Setcontentcharset (UTF8); Client.gEtparams (). Sethttpelementcharset (UTF8);         } public static String get (URL url) {return instance.doget (URL);        } private String doget (url url) {Long beginTime = System.currenttimemillis ();        String respstr = "";        HttpMethod method = null;            try {logger.info (operater_name + "Start get communication, target host:" + URL);            method = new GetMethod (url.tostring ());            Chinese transcoding method.getparams (). Setcontentcharset (UTF8);            try {Client.executemethod (method);                        } catch (HttpException e) {logger.error (new StringBuffer ("Send HTTP get to \ r \ n"). Append (URL)            . Append ("\r\nhttp exception \ r \ n"), E);                        } catch (IOException e) {logger.error (new StringBuffer ("Send HTTP get to \ r \ n"). Append (URL)            . Append ("\r\nio exception \ r \ n"), E); } if (Method.getstatuscode () = = SUCCESS) {respstr = Method.getresponsebodyasstrING ();            } logger.info (Operater_name + "Communication Complete, Return code:" + Method.getstatuscode ());            Logger.info (Operater_name + "return content:" + method.getresponsebodyasstring ()); Logger.info (Operater_name + "End:        Return Result: "+ respstr);        } catch (Exception e) {logger.info (Operater_name, E);            }finally{if (Method! = null) {method.releaseconnection ();        }} Long EndTime = System.currenttimemillis ();        Logger.info (operater_name + "Total time:" + (Endtime-begintime) + "MS");    return respstr; }/** * POST request */public static string post (URL url, String content) {return instance.dopost (URL, CO    Ntent);        } private string doPost (url url, String content) {Long beginTime = System.currenttimemillis ();        String respstr = "";        Postmethod post = null;           try {logger.info (operater_name + "start post communication, target host:" + url.tostring ()); Logger.info ("Communication content:" + content);            Post = new Postmethod (url.tostring ());            Requestentity requestentity = new stringrequestentity (content, Respondtypexml, UTF8);            Post.setrequestentity (requestentity);            Set Format Post.getparams (). Setcontentcharset (UTF8);            Client.executemethod (POST);            if (post.getstatuscode () = = SUCCESS) {respstr = Post.getresponsebodyasstring ();            } logger.info (Operater_name + "Communication Complete, Return code:" + Post.getstatuscode ());            Logger.info (Operater_name + "return content:" + post.getresponsebodyasstring ()); Logger.info (Operater_name + "End:            Return Result: "+ respstr);        Post.releaseconnection ();        } catch (Exception e) {logger.error (Operater_name, E);            }finally{if (post! = null) {post.releaseconnection ();        }} Long EndTime = System.currenttimemillis (); LoggEr.info (operater_name + "Total time:" + (Endtime-begintime) + "MS");    return respstr; }/** * @param args * @throws malformedurlexception */public static void main (string[] args) throws Mal        formedurlexception {//TODO auto-generated method stub jsonobject json = new Jsonobject ();        Json.put ("Mobilecode", "13069208531");        Json.put ("UserID", ""); URL url = new URL ("Http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo");//url url = new URL ("HT Tp://ws.webxml.com.cn/webservices/mobilecodews.asmx "//+"/getmobilecodeinfo?mobilecode=13069208531&useri            D= ");        String resp = post (URL, json.tostring ());        String resp = get (URL);    System.out.println ("RESP:" +resp); }}

HttpClient:

public class Httpclientutil {public static void get (String number) throws exception{HttpClient client = new Ht        Tpclient (); GetMethod get = new GetMethod ("Http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx" + "/getmobilecodeinfo        ? mobilecode= "+ number +" &userid= "); Specifies the format of the transfer as GET request format Get.setrequestheader ("Content-type", "text/xml;        Charset=utf-8 ");        Send request int code = Client.executemethod (GET);        System.out.println ("Http: Status Code:" + code);        String result = Get.getresponsebodyasstring ();    SYSTEM.OUT.PRINTLN ("The result returned is:" + result);        public static void Post (String number) throws Exception {//httpclient: simulates an HTTP request in Java code//creates a browser object        HttpClient client = new HttpClient (); Fill in the data, send a GET or POST request Postmethod post = new Postmethod ("Http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMo        Bilecodeinfo "); Specifies the format of the transfer as the default post format post.setrequestheader ("Content-type", "ApplIcation/x-www-form-urlencoded ");        Transmission parameter Post.setparameter ("Mobilecode", number);        Post.setparameter ("UserID", "");        Send request int code = Client.executemethod (POST);        System.out.println ("Http: Status Code:" + code);        String result = Post.getresponsebodyasstring ();    SYSTEM.OUT.PRINTLN ("The result returned is:" + result); }/** * @Description The SOAP post method request, but the transmitted data is in XML format, facilitates the maintenance of the data * @param number * @throws Exception *//IT    There are two versions of soap1.1 and soap1.2,jdk1.7 and above to use soap1.2. public void Soap (String number) throws Exception {//httpclient: simulates an HTTP request in Java code//creates a browser object Httpclien        T client = new HttpClient ();        Fill in data, send get or POST request Postmethod post = new Postmethod ("Http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx");        Specifies the format of the transfer in XML format Post.setrequestheader ("Content-type", "application/soap+xml;charset=utf-8"); Transfer XML, load soap.txt inputstream in = HttpClientUtil.class.getClassLoader (). GETresourceasstream ("/soap.txt");//The return value is a InputStream post.setrequestbody (in);        Send request int code = Client.executemethod (POST);        System.out.println ("Http: Status Code:" + code);        String result = Post.getresponsebodyasstring ();    If you are using SOAP, the returned data is also the XML-based SOAP format System.out.println ("The result returned is:" + result); }//wsimport-s. -P com.hexy.ws http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?        WSDL public static void wsdl () {//Gets a WS service mobilecodews ws = new Mobilecodews ();        Get the specific service type: Get post soap1.1 soap1.2 mobilecodewssoap wssoap = Ws.getmobilecodewssoap ();        String address = Wssoap.getmobilecodeinfo ("18312345678", null);    SYSTEM.OUT.PRINTLN ("Cell Phone Attribution Information:" + address);        }/** * @param args * @throws Exception */public static void main (string[] args) throws Exception {        TODO auto-generated Method Stub post ("18312345678");        WSDL ();    Soap ("18312345678"); }}

Soap.txt

<?xml version= "1.0" encoding= "Utf-8"? ><soap12:envelope xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:xsd=" Http://www.w3.org/2001/XMLSchema "xmlns:soap12=" http://www.w3.org/2003/05/ Soap-envelope ">  <soap12:Body>    <getmobilecodeinfo xmlns=" http://WebXml.com.cn/">      < mobilecode>13069208531</mobilecode>      <userID></userID>    </getMobileCodeInfo>  </soap12:Body></soap12:Envelope>
Related Article

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.