Send a GET request to a specified URL (Java)

Source: Internet
Author: User

Use Java to send get and post requests
-- Excerpt from crazy Java handout
The openconnection () method of the URL returns a urlconnection object, which indicates the communication link between the application and the URL. The program can send a request to the URL through the urlconnection instance to read the resources referenced by the URL.
Generally, the following steps are required to create a connection with a URL, send a request, and read resources referenced by the URL:
(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:
Qsetallowuserinteraction: set the value of the allowuserinteraction request header field of the urlconnection.
Qsetdoinput: set the value of the doinput request header field of the urlconnection.
Qsetdooutput: set the value of the dooutput request header field of the urlconnection.
Qsetifmodifiedsince: set the value of the ifmodifiedsince request header field of the urlconnection.
Qsetusecaches: 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:
Qsetrequestproperty (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 ","*/*")
Qaddrequestproperty (string key, string value): increases the value of the key request header field of the urlconnection. This method does not overwrite the value of the original request header field, the new value is appended to the original request header field.
When remote resources are available, the program can use the following methods to access header fields and content:

Qobject getcontent (): Get the content of the urlconnection.
Qstring getheaderfield (string name): obtains the value of the specified response header field.
Qgetinputstream (): returns the input stream corresponding to the urlconnection to obtain the content of the urlconnection response.
Qgetoutputstream (): 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:
Qgetcontentencoding: obtains the value of the content-encoding response header field.
Qgetcontentlength: obtains the value of the Content-Length response header field.
Qgetcontenttype: obtains the value of the Content-Type response header field.
Qgetdate (): obtains the value of the date response header field.
Qgetexpiration (): gets the value of the expires response header field.
Qgetlastmodified (): gets 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.

Public class testgetpost
{
/**
* Send a GET request to a specified URL
* @ Param URL the request URL
* @ Param request parameter. The request parameter 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 );
// Open the connection with the URL
Urlconnection conn = realurl. openconnection ();
// Set common request attributes
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 ));
}
// Define 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 finally blocks 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 parameter 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 );
// Open the connection with the URL
Urlconnection conn = realurl. openconnection ();
// Set common request attributes
Conn. setrequestproperty ("accept ","*/*");
Conn. setrequestproperty ("connection", "keep-alive ");
Conn. setrequestproperty ("User-Agent ",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; sv1 )");
// You must set the following two rows to send a POST request:
Conn. setdooutput (true );
Conn. setdoinput (true );
// Obtain the output stream corresponding to the urlconnection object
Out = new printwriter (conn. getoutputstream ());
// Send Request Parameters
Out. Print (PARAM );
// Flush the buffer of the output stream
Out. Flush ();
// Define 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 the POST request! "+ E );
E. printstacktrace ();
}
// Use finally blocks to close output streams and input streams
Finally
{
Try
{
If (OUT! = NULL)
{
Out. Close ();
}
If (in! = NULL)
{
In. Close ();
}
}
Catch (ioexception ex)
{
Ex. printstacktrace ();
}
}
Return result;
}

// Provides the primary method to test sending GET requests and post requests
Public static void main (string ARGs [])
{
// Send a GET request
String S = testgetpost. sendget ("http: // localhost: 8888/ABC/login. jsp", null );
System. Out. println (s );
// Send a POST request
String S1 = testgetpost. sendpost (http: // localhost: 8888/ABC/a. 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 directly calls the Connect Method of the urlconnection object, as shown in the bold text code in the sendget method in the program. If the program needs to send a POST request, you must first set the values of the doin and doout request header fields, and then use the output stream corresponding to urlconnection to send request parameters, as shown in the bold text code in the sendpost method in the program.
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, it can use the response stream to read the response; if the program cannot determine that the remote response is a response stream, use the byte stream to read the response.
Note: The two URLs in the above program send requests are Web applications deployed on the local machine by the author, for more information about how to create web applications and compile JSP pages, see the author's Lightweight J2EE enterprise application practice. Because the program can directly send a request to the server in this way, it is equivalent to submitting a login table page in the Web application, so that the program can continuously change the user name and password to submit the login request, 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.