Java for post and get pass parameters

Source: Internet
Author: User

Http://www.cnblogs.com/zhuawang/archive/2012/12/08/2809380.html

Get and Post methods

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 {/** * a request to send a GET method to a specified URL * * @param URL * Send the requested URL * @param pa     RAM * 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.        * The response result of the remote resource represented by the @return */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 parameters         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.getinput            Stream ()));            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; }    }

Call
public static void Main (string[] args) {        //Send GET request        String s=httprequest.sendget ("http://localhost:6144/Home/ RequestString "," key=123&v=456 ");        System.out.println (s);                Send POST request        String sr=httprequest.sendpost ("http://localhost:6144/Home/RequestPostString", "key=123&v=456 ");        System.out.println (SR);    }

2. Post method

Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.outputstreamwriter;import Java.net.httpurlconnection;import Java.net.URL;                 public class Test {public static void main (string[] args) throws IOException {String urlstr = "HTTP://TRANSLATE.GOOGLEAPIS.COM/TRANSLATE_A/T?" + "anno=3&client=te&format=html&v=1.0&logld=v10        ";        URL url = new URL (urlstr);        HttpURLConnection conn = (httpurlconnection) url.openconnection ();    Conn.setdooutput (TRUE);    can send data conn.setdoinput (TRUE);    can receive data Conn.setrequestmethod ("POST"); Post method//must be noted here to set useragent, otherwise Google will return 403 conn.setrequestproperty ("User-agent", "mozilla/4.0 ( Compatible MSIE 6.0;        Windows NT 5.0) ");        Conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");        Conn.connect (); Write the Post data outputstreamwRiter OSW = new OutputStreamWriter (Conn.getoutputstream (), "UTF-8");        Osw.write ("q= China &sl=auto&tl=en&tc=1");        Osw.flush ();        Osw.close ();        Read response data BufferedReader in = new BufferedReader (New InputStreamReader (Conn.getinputstream ()));        String s;    while ((s = in.readline ()) = null) System.out.println (s); }}

Java for post and get pass parameters

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.