HttpRequest

Introduction

Essentially, the get and post utility methods in HttpUtil are encapsulations of the HttpRequest object. Therefore, if you want more flexible operation of HTTP requests, you can use HttpRequest.

Usage

Ordinary Form

Let’s take a POST request as an example:

// Chained request construction
String result2 = HttpRequest.post(url)
    .header(Header.USER_AGENT, "Hutool http") // Header information, multiple header information can be set by calling this method multiple times
    .form(paramMap) // Form content
    .timeout(20000) // Timeout in milliseconds
    .execute().body();
Console.log(result2);

By chaining the request construction, we can easily specify HTTP header information and form information. Finally, we call the execute method to perform the request and return an HttpResponse object. HttpResponse contains some information about the server response, including the response content and response header information. We can obtain the response content by calling the body method.

Restful Request

String json = ...;
String result2 = HttpRequest.post(url)
    .body(json)
    .execute().body();

Configuring Proxy

If the proxy does not require a username and password, you can directly use:

String result2 = HttpRequest.post(url)
    .setHttpProxy("127.0.0.1", 9080)
    .body(json)
    .execute().body();

If you need to customize other types of proxies or more items, you can use:

String result2 = HttpRequest.post(url)
    .setProxy(new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(host, port))
    .body(json)
    .execute().body();

If you encounter an HTTPS proxy error Proxy returns "HTTP/1.0 407 Proxy Authentication Required", you can try:

System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
Authenticator.setDefault(
    new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
              return new PasswordAuthentication(authUser, authPassword.toCharArray());
        }
    }
);

Other Customizations

Similarly, we can easily perform the following operations through HttpRequest:

  • Specify request headers
  • Customize Cookies (cookie method)
  • Specify whether to keepAlive (keepAlive method)
  • Specify form content (form method)
  • Specify request content, such as specifying a JSON request body for REST requests (body method)
  • Timeout settings (timeout method)
  • Specify proxy (setProxy method)
  • Specify SSL protocol (setSSLProtocol)
  • Simple authentication (basicAuth method)