Java sends get,post requests

Source: Internet
Author: User
Tags getmessage response code

There are comments in the method: Refer to the csdn inside, the project time to change their own

 Packagecom.bst.express;ImportJava.io.BufferedReader;ImportJava.io.DataOutputStream;Importjava.io.IOException;ImportJava.io.InputStreamReader;Importjava.net.HttpURLConnection;Importjava.net.MalformedURLException;ImportJava.net.URL;Importorg.junit.Test; Public classHttptools { Public Static FinalString Get_url = "http://192.168.1.61";  Public Static FinalString post_url = "Http://localhost:8080/wayBill/common/api"; /*** GET Request*/@Test Public  voidHttpurlconectionget () {Try{URL URL=NewURL (Get_url);//The string is converted to the request addressHttpURLConnection connection = (httpurlconnection) url.openconnection ();//Open ConnectionConnection.connect ();//Connection SessionBufferedReader br =NewBufferedReader (NewInputStreamReader (Connection.getinputstream (), "UTF-8"));//The response result is an input streamString Line; StringBuilder SB=NewStringBuilder ();//results of the output             while(line = Br.readline ())! =NULL) {sb.append (line);            } br.close (); Connection.disconnect ();//Disconnect ConnectionSystem.out.println (sb.tostring ()); } Catch(Exception e) {e.printstacktrace (); System.out.println ("Request failed:" +e.getmessage ()); }    }    /*** POST Request*/@Test Public  voidHttpurlconnectionpost () {Try{URL URL=NewURL (Post_url); //1. URLConnection The URL returned by the Open method//connection strong to HttpURLConnection connection. At this point the cnnection is just a connection object, pending connectionHttpURLConnection connection =(HttpURLConnection) url.openconnection (); //2. Set the connection output stream to True, default False (the POST request is a stream implicitly passed parameter)Connection.setdooutput (true); //3. Set the connection input stream to TrueConnection.setdoinput (true); //4. Set the request mode to postConnection.setrequestmethod ("POST"); //5.post Request Cache set to FalseConnection.setusecaches (false); /** 6. Set the various properties within the request header (the following is the type of the set content, set to the urlencoded encoded from parameter) * Application/xml:xml data, application/ Json:json Object * text/html: Form data*/Connection.setrequestproperty ("Content-type", "Application/json;charset=utf-8"); //7. Establish a connection//(the request does not start until the Connection.getinputstream () method call is initiated, and the above parameters are set before this method)Connection.connect (); //8. Create an input/output stream for outputting the parameters that are carried in the connection, (the output is the following)DataOutputStream dataout =NewDataOutputStream (Connection.getoutputstream ()); //9. Enter the parameter: JSON formatString parm = "{\" pubrequest\ ": {\" token\ ": \" 121212\ ", \" method\ ": \" auth.login\ "," + "\" version\ ": \" 1.0\ " , \ "encrytype\": \ "6\"},\ "body\": {\ "account\": \ "18584084561\", "+" \ "password\": \ "123456\"}} "; //10. Output parameters to the connectiondataout.writebytes (parm); //refresh and close the stream when the output is completeDataout.flush (); Dataout.close (); //important and easy to ignore steps (close the stream, remember!) //System.out.println ("Response Code:" +connection.getresponsecode ()); //Connection initiation request, processing server response (from connection fetch to input stream and wrapped as BufferedReader)BufferedReader BF =NewBufferedReader (NewInputStreamReader (Connection.getinputstream (), "UTF-8"));            String Line; StringBuilder SB=NewStringBuilder ();//used to store response data//Loop read stream, if not at the end             while(line = Bf.readline ())! =NULL) {sb.append (line);//to wrap: sb.append (line). Append (System.getproperty ("Line.separator")); } bf.close (); //important and easy to ignore steps (close the stream, remember!)Connection.disconnect ();//Destroy ConnectionSystem.out.println (sb.tostring ()); } Catch(Exception e) {e.printstacktrace (); System.out.println ("Request failed:" +e.getmessage ()); }    }}

Java sends get,post requests

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.