Use the Java built-in class HttpUrlConnection to implement HTTP requests

Source: Internet
Author: User

Use the Java built-in class HttpUrlConnection to implement HTTP requests

1. Overview

In this quick tutorial, we will use the Java built-in class HttpUrlConnection to implement an Http request.

2. HttpUrlConnection

The HttpUrlConnection class allows us to implement basic Http requests without adding any other class libraries. All required classes are included in the java.net package. The disadvantage is that compared with other http class libraries, this method is a little cumbersome and does not provide APIs with some advanced features, such as adding request headers and adding authentication. But it doesn't matter. You can encapsulate this implementation, and it is not very complicated to add some advanced features.

If you just want to make some Http requests quickly without adding some class libraries, the code in this article is enough.

In addition, if you do not know much about the java http request implementation, the Code provided in this article will also be helpful.

3. Create a request

The HttpUrlConnection class is created through the openConnection () method of the URL class. This method only creates a connection object and does not establish a connection.

By setting the requestMethod attribute, the HttpUrlConnection class can create various request types, including GET, POST, HEAD, OPTIONS, PUT, DELETE, and TRACE.

For example, create a GET request:

URL url = new URL ("www.bkjia.com ");
HttpURLConnection con = (HttpURLConnection) url. openConnection ();
Con. setRequestMethod ("GET ");

4. Add Request Parameters

If we want to add request parameters, we need to set doOutput to true, and then splice the request parameters into strings in the format of param1 = value & param2 = value, write Data to the OutputStream of the HttpUrlConnection instance as a stream. The sample code is as follows:

Map <String, String> parameters = new HashMap <> ();
Parameters. put ("param1", "val ");
 
Con. setDoOutput (true );
DataOutputStream out = new DataOutputStream (con. getOutputStream ());
Out. writeBytes (ParameterStringBuilder. getParamsString (parameters ));
Out. flush ();
Out. close ();

To facilitate the conversion of string parameters, I wrote a tool class ParameterStringBuilder. Class contains a static method getParamsString () to convert Map to the corresponding format string:

Public class ParameterStringBuilder {
Public static String getParamsString (Map <String, String> params)
Throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder ();
 
For (Map. Entry <String, String> entry: params. entrySet ()){
Result. append (URLEncoder. encode (entry. getKey (), "UTF-8 "));
Result. append ("= ");
Result. append (URLEncoder. encode (entry. getValue (), "UTF-8 "));
Result. append ("&");
}
 
String resultString = result. toString ();
Return resultString. length ()> 0
? ResultString. substring (0, resultString. length ()-1)
: ResultString;
}
}

5. Add a Request Header

You can use setRequestProperty () to add a request header:

Con. setRequestProperty ("Content-Type", "application/json ");

The getHeaderField () method can be used to read the response header:

String contentType = con. getHeaderField ("Content-Type ");

6. Configure the timeout time

Class allows us to set the connection timeout and read timeout. These values determine the maximum wait time for a connection to be established or the maximum wait time for reading data.

Set the timeout time. We can call the setConnectTimeout () method and the setReadTimeout () method ():

Con. setConnectTimeout (5000 );
Con. setReadTimeout (5000 );

In this example, we set the timeout time to 5 seconds.

7. Process Cookies

The classes CookieManager and HttpCookie contained in the java.net package can easily process Cookies.

First, read cookies from the response. First, we get the Set-Cookie value in the corresponding header, and then parse it into the List of HttpCookie objects.

String cookiesHeader = con. getHeaderField ("Set-Cookie ");
List <HttpCookie> cookies = HttpCookie. parse (cookiesHeader );

Next, we store cookies:

Cookies. forEach (cookie-> cookieManager. getCookieStore (). add (null, cookie ));

We check whether the cookies contain a username attribute. If not, we add a username named zhangsan:

Optional <HttpCookie> usernameCookie = cookies. stream ()
. FindAny (). filter (cookie-> cookie. getName (). equals ("username "));
If (usernameCookie = null ){
CookieManager. getCookieStore (). add (null, new HttpCookie ("username", "john "));
}

Finally, add cookies to the request. We need to add the Cookie request header after closing the connection and re-opening the connection:

Con. disconnect ();
Con = (HttpURLConnection) url. openConnection ();
Con. setRequestProperty ("Cookie ",
StringUtils. join (cookieManager. getCookieStore (). getCookies (),";"));

8. Process redirection

You can set setInstanceFollowRedirects () to true or false to determine whether to allow a specific connection to automatically follow redirection:

Con. setInstanceFollowRedirects (false );

You can also set whether all connections allow automatic redirection:

HttpUrlConnection. setFollowRedirects (false );

Automatic redirection is allowed by default.

Request return status code 301,302 indicates redirection. We can obtain the Location attribute of the response header and create a new connection with the new URL.

If (status = HttpURLConnection. HTTP_MOVED_TEMP
| Status = HttpURLConnection. HTTP_MOVED_PERM ){
String location = con. getHeaderField ("Location ");
URL newUrl = new URL (location );
Con = (HttpURLConnection) newUrl. openConnection ();
}

9. Read response

Read the response by reading the InputStream stream of the HttpUrlConnection instance.

Common Methods for reading responses include getResponseCode (), connect (), getInputStream () or getOutputStream ().

For example, read the response status code:

Int status = con. getResponseCode ();

For example, read the response header:

String contentType = con. getHeaderField ("Content-Type ");

For example, read the response text:

BufferedReader in = new BufferedReader (
New InputStreamReader (con. getInputStream ()));
String inputLine;
StringBuffer content = new StringBuffer ();
While (inputLine = in. readLine ())! = Null ){
Content. append (inputLine );
}
In. close ();

Close connection:

Con. disconnect ();

Conclusion

In this article, we show how to use the HttpUrlConnection class to time Http requests. The following code can be directly copied and used. Because it is too simple, we will not upload github.

Package com. bkjia. utils;

Import java. io .*;
Import java.net. HttpURLConnection;
Import java.net. URL;
Import java.net. URLEncoder;
Import java. util. HashMap;
Import java. util. Map;

Public class HttpUtil {

Private static String POST = "POST ";
Private static String GET = "GET ";
Private static String CONTENT_TYPE_URLENCODED = "application/x-www-form-urlencoded ";
Private static String CONTENT_TYPE_JSON = "application/json ";

Private static String httpRequest (String method, String contentType, String urlStr, HashMap <String, String> paras)
Throws IOException {
URL url = new URL (urlStr );
HttpURLConnection con = (HttpURLConnection) url. openConnection ();
Con. setConnectTimeout (5000 );
Con. setReadTimeout (5000 );
Con. setRequestMethod ("POST ");
Con. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded ");

If (paras! = Null &&! Paras. isEmpty ()){
Con. setDoOutput (true );
DataOutputStream out = new DataOutputStream (con. getOutputStream ());
Out. writeBytes (ParameterStringBuilder. getParamsString (paras ));
Out. flush ();
Out. close ();
}

BufferedReader in = new BufferedReader (new InputStreamReader (con. getInputStream ()));
String inputLine;
StringBuffer content = new StringBuffer ();
While (inputLine = in. readLine ())! = Null ){
Content. append (inputLine );
}
In. close ();
Con. disconnect ();
Return content. toString ();
}

Private static class ParameterStringBuilder {
Public static String getParamsString (Map <String, String> params)
Throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder ();

For (Map. Entry <String, String> entry: params. entrySet ()){
Result. append (URLEncoder. encode (entry. getKey (), "UTF-8 "));
Result. append ("= ");
Result. append (URLEncoder. encode (entry. getValue (), "UTF-8 "));
Result. append ("&");
}

String resultString = result. toString ();
Return resultString. length ()> 0
? ResultString. substring (0, resultString. length ()-1)
: ResultString;
}
}


Public static String httpGetRequest (String url ){
Try {
Return httpRequest (GET, CONTENT_TYPE_URLENCODED, url, null );
} Catch (IOException e ){
E. printStackTrace ();
}
Return "";
}

Public static String httpPostRequest (String url, HashMap <String, String> paras ){
Try {
Return httpRequest (POST, CONTENT_TYPE_URLENCODED, url, paras );
} Catch (IOException e ){
E. printStackTrace ();
}
Return "";
}
}

This article permanently updates link: https://www.bkjia.com/Linux/2018-03/151204.htm

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.