Java Send HttpRequest

Source: Internet
Author: User

What is HTTP? Hypertext Transfer Protocol (Hypertext Transfer Protocol-HTTP) is a protocol designed to enable clients and servers to communicate smoothly. HTTP works with Request-response protocol (Request-reply protocol) between the client and the server. Get and post are the two common methods of HTTP. Get-gets data from the specified server post-submits data to the specified server to handle the GET method: When using the Get method, the query string (key-value pair) is appended to the URL address and sent to the server:/test/demo_form.jsp?name1= Value1&name2=value2 Features:
    • Get requests can be cached
    • Get requests are saved in the browser's browsing history
    • URL with Get request can be saved as browser bookmark
    • Get request has a length limit
    • Get requests are primarily used to obtain data
Post method: When using the Post method, the query string exists separately in the post message and is sent to the server with the HTTP request: post/test/demo_form.jsp http/1.1host:w3schools.comname1= Value1&name2=value2 Features:
    • Post requests cannot be cached
    • Post requests are not saved in browser browsing history
    • The URL to post request cannot be saved as a browser bookmark
    • POST request has no length limit
The difference between get and post:
GET POST
Click the Back/Refresh button No impact The data will be resent (the browser will prompt the user "data is being resubmitted")
Add Bookmark OK No
Cache OK No
Encoding type (Encoding type) application/x-www-form-urlencoded Application/x-www-form-urlencoded or Multipart/form-data. Please use multipart encoding for binary data
Historical records Yes No
Length limit Yes No
Data type Restrictions Only ASCII character types are allowed There is no limit. Allows binary data
Security The query string is displayed in the URL of the address bar and is not secure, please do not submit sensitive data using GET requests Since the data is not displayed in the address bar and is not cached or saved in the browsing history, it is safer to look at the post than the GET request, but it is not the safest way. If you need to transfer sensitive data, use encrypted mode to transfer
Visibility of The query string is displayed in the URL of the address bar, visible The query string is not displayed in the Address bar, not visible
Other HTTP request methods
Way Describe
HEAD Similar to get requests, unlike a server that only returns HTTP header information, no page content
PUT Upload a description of the specified URL
DELETE Delete a specified resource
OPTIONS Returns the HTTP methods supported by the server
CONNECT Connection request converted to transparent TCP/IP tunneling
The Java implementation code for sending get and post requests is as follows
 PackageWzh. Http;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.URL;Importjava.net.URLConnection;Importjava.util.List;ImportJava.util.Map; Public classHttpRequest {/*** A request to send a GET method to a specified URL *@paramURL * URL to send request *@paramparam * Request parameters, request parameters should be in the form of name1=value1&name2=value2. * @returnThe response result of the remote resource represented by the URL*/     Public Staticstring sendget (string url, string param) {string result= ""; BufferedReader in=NULL; Try{String urlnamestring= URL + "?" +param; URL Realurl=NewURL (urlnamestring); //opening and linking between URLsURLConnection connection =realurl.openconnection (); //to set common request propertiesConnection.setrequestproperty ("Accept", "*/*"); Connection.setrequestproperty ("Connection", "keep-alive"); Connection.setrequestproperty ("User-agent",                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) "); //establish an actual connectionConnection.connect (); //Get all response header fieldsmap<string, list<string>> map =Connection.getheaderfields (); //iterate through all the response header fields             for(String key:map.keySet ()) {System.out.println (key+ "--->" +Map.get (key)); }            //defines the response of the BufferedReader input stream to read the URLin =NewBufferedReader (NewInputStreamReader (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 the finally block to close the input stream        finally {            Try {                if(In! =NULL) {in.close (); }            } Catch(Exception E2) {e2.printstacktrace (); }        }        returnresult; }    /*** Request to send the Post method to the specified URL * *@paramURL * URL to send request *@paramparam * Request parameters, request parameters should be in the form of name1=value1&name2=value2. * @returnThe response result of the remote resource represented*/     Public Staticstring sendpost (string url, string param) {PrintWriter out=NULL; BufferedReader in=NULL; String result= ""; Try{URL Realurl=Newurl (URL); //opening and linking between URLsURLConnection conn =realurl.openconnection (); //to set common request propertiesConn.setrequestproperty ("Accept", "*/*"); Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("User-agent",                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) "); //to send a POST request, you must set the following two linesConn.setdooutput (true); Conn.setdoinput (true); //gets the output stream corresponding to the URLConnection objectout =NewPrintWriter (Conn.getoutputstream ()); //Send Request Parametersout.print (param); //buffer for flush output streamOut.flush (); //defines the response of the BufferedReader input stream to read the URLin =NewBufferedReader (NewInputStreamReader (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 the 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 (); }        }        returnresult; }    }

Calling methods

 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 a POST request        String sr=httprequest.sendpost ("http://localhost:6144/Home/RequestPostString", "key=123&v=456");        System.out.println (SR);    }
View Code

Java Send HttpRequest

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.