Java URL request

Source: Internet
Author: User

Use Java to send get and post requests-Excerpted from crazy Java Handouts
The openconnection () method of the URL returns a urlconnection object, which indicates that the application and
The communication link between URLs. The program can send a request to the URL through the urlconnection instance to read the resources referenced by the URL.

Usually create a URL
And send a request to read this URL.
The following steps are required for referenced resources:
(1) create a urlconnection object by calling the URL object openconnection () method.
(2) Set urlconnection parameters and common request attributes.
(3) If you only send a GET request, you can use the connect method to establish an actual connection with a remote resource. If you need to send a POST request, you need to obtain the output stream corresponding to the urlconnection instance to send request parameters.

(4) When the remote resource becomes available, the program can access the header field of the Remote resource or read the data of the Remote resource through the input stream.

Before establishing an actual connection to a remote resource, the program can set the request header field as follows:
Setallowuserinteraction: set the value of the allowuserinteraction request header field of the urlconnection. [If this parameter is set to true, check the URL in the context that allows user interaction (for example, a validation dialog box pops up]
Setdoinput: set the value of the doinput request header field of the urlconnection. [Set input content]
Setdooutput: set the value of the dooutput request header field of the urlconnection. [Set output content]
Setifmodifiedsince: set the value of the ifmodifiedsince request header field of the urlconnection.
Setusecaches: set the value of the usecaches request header field of the urlconnection.

In addition, you can use the following method to set or add a common header field:
Setrequestproperty (string
Key, string
Value): set the value of the key request header field of the urlconnection to value. The following code is used:
Conn. setrequestproperty ("accept"
,"*/*")

Addrequestproperty (string key, string
Value): adds a value to the key request header field of the urlconnection. This method does not overwrite the value of the original request header field, but adds the new value to the original request header field.

When remote resources are available, the program can use the following methods to access header fields and content:

 

Object getcontent (): Get the content of the urlconnection.
String getheaderfield (string
Name): obtains the value of the specified response header field.
Getinputstream (): returns the input stream corresponding to the urlconnection to obtain the content 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 urlconnection response content and the output stream to send request parameters, 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. Some header fields are frequently accessed, so Java provides the following methods to access the values of specific response header fields:
Getcontentencoding: obtains the value of the content-encoding response header field.
Getcontentlength: Get the value of the Content-Length response header field.
Getcontenttype: Get the value of the Content-Type response header field.
Getdate (): Get the value of the date response header field.
Getexpiration (): Get the value of the expires response header field.
Getlastmodified (): Get the value of the last-modified response header field.

The following example shows how to send a GET request and a POST request to a Web site and obtain a response from the Web site.

 

Import Java. io. *; import java.net. *; import Java. util. *; public class testgetpost {/*** send a get Method Request to a specified URL * @ Param URL send the request URL * @ Param request parameter, the request parameters should be in the form of name1 = value1 & name2 = value2. * @ Return URL indicates the response of the Remote resource */public static string sendget (string URL, string PARAM) {string result = ""; bufferedreader in = NULL; try {string urlname = URL + "? "+ Param; Url realurl = new URL (urlname); // enable the URL Connection urlconnection conn = realurl. openconnection (); // set 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)"); // establish the actual connection Conn. connect (); // obtain all response header fields Map <string, list <string> map = Conn. getheaderfields (); // Traverse all response header fields for (string key: map. keyset () {system. out. println (Key + "--->" + map. get (key);} // defines the bufferedreader input stream to read the URL response in = new bufferedreader (New inputstreamreader (Conn. getinputstream (); string line; while (line = in. readline ())! = NULL) {result + = "\ n" + line;} catch (exception e) {system. Out. println ("an exception occurred when sending a GET request! "+ E); E. printstacktrace () ;}// use the Finally block to close the input stream finally {try {If (in! = NULL) {In. close () ;}} catch (ioexception ex) {ex. printstacktrace () ;}} return result;}/*** send a POST method request to a specified URL * @ Param URL the request URL * @ Param request parameter, the request parameters should be in the form of name1 = value1 & name2 = value2. * @ Return URL indicates the response of the Remote resource */public static string sendpost (string URL, string PARAM) {printwriter out = NULL; bufferedreader in = NULL; string result = ""; try {URL realurl = new URL (URL); // enable the URL Connection urlconnection conn = realurl. openconnection (); // set the common request attribute Conn. setrequestproperty ("accept", "*/*"); Conn. setrequestproperty ("connection", "keep-alive"); Conn. setrequestproperty ("User-Agent", "mozil La/4.0 (compatible; MSIE 6.0; Windows NT 5.1; sv1) "); // The following two rows of conn must be set to send a POST request. setdooutput (true); Conn. setdoinput (true); // get the output stream of the urlconnection object out = new printwriter (Conn. getoutputstream (); // sends the request parameter out. print (PARAM); // flush the Buffer out of the output stream. flush (); // defines the bufferedreader input stream to read the URL response in = new bufferedreader (New inputstreamreader (Conn. getinputstream (); string line; while (line = in. readline ())! = NULL) {result + = "\ n" + line;} catch (exception e) {system. Out. println ("an exception occurred when sending a POST request! "+ E); E. printstacktrace () ;}// use finally blocks to close the output stream and input stream finally {try {If (OUT! = NULL) {out. Close () ;}if (in! = NULL) {In. close () ;}} catch (ioexception ex) {ex. printstacktrace () ;}} return result;} // provides the main method to test the public static void main (string ARGs []) Request for sending GET requests and post requests. {// send the GET request string S = testgetpost. sendget ("http: // localhost: 8888/ABC/login. JSP ", null); system. out. println (s); // send the POST request string S1 = testgetpost. sendpost ("http: // localhost: 8888/ABC/. JSP "," user = Li Gang & pass = ABC "); system. out. println (S1 );}}

When sending a GET request in the above program, you only need to put the request parameters after the URL string? The program can directly call the Connect Method of the urlconnection object. If the program needs to send a POST request, you must first set the values of the doin and doout request header fields, use the output stream corresponding to urlconnection to send request parameters.

Whether sending a GET request or a POST request, the program obtains the urlconnection response in the same way: if the program can determine that the remote response is a response stream, you can
To use the response stream for reading. If the program cannot determine that the remote response is a response stream, use the byte stream for reading.

Note: The two URLs in the above program send requests are Web applications deployed on the local machine by the author, because the program can directly send requests to the server in this way-equivalent to submitting login tables in the Web Application
Single page, so that the program can constantly change the user name and password to submit the login request until a successful login is returned. This is called brute force cracking.

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.