The OpenConnection () method of the URL returns a URLConnection object that represents the communication link between the application and the URL. The program can send requests to the URL through the URLConnection instance and read the resource referenced by the URL.
Typically creating a connection to a URL and sending a request, reading the resource referenced by this URL requires the following steps:
(1) Create a URLConnection object by calling the URL object OpenConnection () method.
(2) Set the parameters of the URLConnection and the normal request properties.
(3) If you just send a Get method request, use the Connect method to establish an actual connection between the remote resources, and if you need to send a post-mode request, you need to get the output stream for the URLConnection instance to send the request parameters.
(4) The remote resource becomes available, the program can access the remote resource's header field, or read the remote resource's data through the input stream.
Before establishing an actual connection to a remote resource, the program can set the request header field as follows:
Setallowuserinteraction: Sets the value of the allowUserInteraction Request header field for this urlconnection.
Setdoinput: Sets the value of the Doinput Request header field for this urlconnection.
Setdooutput: Sets the value of the Dooutput Request header field for this urlconnection.
Setifmodifiedsince: Sets the value of the Ifmodifiedsince Request header field for this urlconnection.
Setusecaches: Sets the value of the Usecaches Request header field for this urlconnection.
In addition, you can use the following methods to set or add a common header field:
Setrequestproperty (string key, String value): Sets the value of the key Request header field for the URLConnection. As shown in the following code:
Conn.setrequestproperty ("Accept", "*/*")
Addrequestproperty (string key, String value): Adds value to the URLConnection's key request header field, which does not overwrite the value of the original request header field, but appends the new value to the original Request header field.
When a remote resource is available, the program can use the following methods to access the header fields and content:
Object getcontent (): Gets the contents of the URLConnection.
String Getheaderfield (string name): Gets the value of the specified response header field.
getInputStream (): Returns the input stream corresponding to the URLConnection, which is used to obtain the contents of the URLConnection response.
Getoutputstream (): Returns the output stream corresponding to the URLConnection, which is used to send request parameters to URLConnection.
Note: If you want to use the input stream to read the contents of the URLConnection response and send the request parameters using the output stream, you must first use the output stream before using the input stream.
The Getheaderfield method is used to return the corresponding value based on the response header field. While some header fields often require access, Java provides the following methods to access the values of a specific response header field:
Getcontentencoding: Gets the value of the Content-encoding response header field.
Getcontentlength: Gets the value of the Content-length response header field.
getContentType: Gets the value of the Content-type response header field.
GetDate (): Gets the value of the date response header field.
Getexpiration (): Gets the value of the Expires Response header field.
Getlastmodified (): Gets the value of the Last-modified response header field.
The following procedure shows an example of how to send a GET request, a POST request, and a response from a Web site to a Web site.
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 classMain {/*** 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 of the remote resource represented by the URL*/ Public Staticstring sendget (string url, string param) {string result= ""; BufferedReader in=NULL; Try{String urlname= URL + "?" +param; URL Realurl=NewURL (urlname); //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) "); //establish an actual connectionConn.connect (); //Get all response header fieldsmap<string, list<string>> map =Conn.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 (Conn.getinputstream ())); String Line; while(line = In.readline ())! =NULL) {result+ = "/n" +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(IOException ex) {ex.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 of the remote resource represented by the URL*/ 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+ = "/n" +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; } //provide the main method, test send GET request and POST request Public Static voidMain (String args[]) {//send a GET request /*String s = Main.sendget ("http://localhost: 8080/webdemo ", null); System.out.println (s);*/ //send a POST requestString S1 = main.sendpost ("Http://localhost:8080/webdemo", "User= Li Gang &pass=abc"); System.out.println (S1); }}
In the above program to send a GET request only need to put the request parameters after the URL string, separated by, the program directly calls the URLConnection object's Connect method, such as the program in the Sendget method of the bold code, as shown; if the program needs to send a POST request, You need to set the values of the doin and Doout two request header fields before sending the request parameters using the urlconnection corresponding output stream, as shown in the bold code in the Sendpost method in the program.
Whether you send a GET request or send a POST request, the program gets the URLConnection response exactly the same way: if the program can determine that the remote response is a character stream, you can use a character stream to read, or if the program cannot determine that the remote response is a character stream, use a byte stream to read it.
This article is from http://blog.csdn.net/iijse/article/details/6201101 original link: http://edu.codepub.com/2009/1027/16842_2.php
Use URLConnection to send post and get requests