Java uses post and get methods to submit HTTP requests Universal __java

Source: Internet
Author: User
Tags finally block flush readline

Many APIs provide a Java Post,get way to invoke the interface that returns the result, and the following records are common for sending requests and receiving return parameters:

Package com.taray.test;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import Java.net.URL;
Import java.net.URLConnection;
Import java.util.List;

Import Java.util.Map; public class HttpRequest {/** * request to send a GET method to the specified URL * * @param URL * Send the requested URL * @pa
     RAM param * Request parameters, request parameters should be in the form of name1=value1&name2=value2. * @return The response result of the remote resource represented by the URL/public static string Sendget (string URL, string param) {String results = ""
        ;
        BufferedReader in = null;
            try {String urlnamestring = URL + '? ' + param;
            URL realurl = new URL (urlnamestring);
            The connection between open and URL urlconnection connection = Realurl.openconnection ();
            Sets the common 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 ();
            Gets all response header fields Map<string, list<string>> Map = Connection.getheaderfields (); Iterate through all the response header fields for (String Key:map.keySet ()) {System.out.println (key +--->) + map.get (k
            EY));
                    }//define BufferedReader input stream to read URL response in = new BufferedReader (New InputStreamReader (
            Connection.getinputstream ()));
            String Line;
            while (line = In.readline ())!= null) {result + = line; 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
                . Close (); Catch (Exception E2)
            {E2.printstacktrace ();
    } return result; /** * Request * Sending the Post method to the specified URL * @param URL to send the requested URL * @param param request parameter, the request parameter should be name1=value1&name2=
     The form of value2. * The response result of the remote resource represented by the @return/public static string Sendpost (string url, string param) {PrintWriter out = nul
        L
        BufferedReader in = null;
        String result = "";
            try {URL realurl = new URL (URL);
            The connection between open and URL URLConnection conn = realurl.openconnection ();
            Sets the common 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); 1. Get URLConnection object corresponding to output stream out = new PrintwriteR (Conn.getoutputstream ()); 2. Chinese have garbled need to change printwriter to the following//out=new OutputStreamWriter (Conn.getoutputstream (), "UTF-8")//Send request parameter
            Number Out.print (param);
            Flush output Stream Buffer Out.flush ();
            Defines the response of the BufferedReader input stream to read the URL in = new BufferedReader (New InputStreamReader (Conn.getinputstream ()));
            String Line;
            while (line = In.readline ())!= null) {result + = line; Exception e {System.out.println ("send POST request exception.
            "+e);
        E.printstacktrace (); ///Use finally block to turn off output stream, input stream finally{try{if (out!=null) {out.
                Close ();
                } if (In!=null) {in.close ();
            } catch (IOException ex) {ex.printstacktrace (); } System.out.println ("Post push Result:"+result);
    return result; public static void Main (string[] args) {//Send GET request String s=httprequest.sendget ("http://local
        Host:6144/home/requeststring "," key=123&v=456 ");
        
        System.out.println (s);
        Send a POST request String sr=httprequest.sendpost ("http://localhost:6144/Home/RequestPostString", "key=123&v=456");
    System.out.println (SR); }
}

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.