Have you learned all four ways to implement HTTP requests in Java?

Preface

In daily work and study, there are many places where HTTP requests need to be sent. This article uses Java as an example to summarize the various ways of sending HTTP requests.

HTTP request implementation process

GET

  • Create remote connection

  • Set the connection method (get, post, put...)

  • Set connection timeout

  • Set response read time

  • Make a request

  • Get request data

  • close connection

POST

  • Create remote connection

  • Set the connection method (get, post, put...)

  • Set connection timeout

  • Set response read time

  • When transmitting/writing data to the remote server, it needs to be set totrue(setDoOutput)

  • When reading data from the remote service, set to true. This parameter is optional ( setDoInput)

  • Set the format of the incoming parameters: ( setRequestProperty)

  • Set authentication information:Authorization:(setRequestProperty)

  • Setting parameters

  • Make a request

  • Get request data

  • close connection

1. Use the HttpURLConnection class

HttpURLConnection It is a class in the Java standard library used to send HTTP requests and receive HTTP responses.

It pre-defines some methods, such as  setRequestMethod(), setRequestProperty() and  getResponseCode(), to facilitate developers to freely control requests and responses.

Sample code:

import java.net.*;
import java.io.*;

public class HttpURLConnectionExample {

    private static HttpURLConnection con;

    public static void main(String[] args) throws Exception {

        URL url = new URL("https://www.example.com");
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");

        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();

        System.out.println(content.toString());
    }
}

2. Use HttpClient library

HttpClient is an HTTP client library that provides methods for sending requests to HTTP servers and processing responses.

It supports multiple request protocols, such as GET, POST, etc., and allows developers to freely set request headers, request parameters, connection pools, etc. HttpClient also provides asynchronous request processing based on thread pool.

Sample code:

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientExample {

    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet("https://www.example.com");
        CloseableHttpResponse response = httpclient.execute(httpget);

        try {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            EntityUtils.consume(entity);

            System.out.println(result);
        } finally {
            response.close();
        }
    }
}

3. Use Okhttp library

Okhttp is a lightweight network request library developed by Square. It supports ordinary HTTP/1.1 and SPDY and can be used with network request frameworks such as Retrofit.

Sample code:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

public class OkhttpExample {

    private static final OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) throws IOException {
        Request request = new Request.builder()
         .url("https://www.example.com")
         .build();
        try (Response response = client.newCall(request).execute()) {
            String result = response.body().string();
            System.out.println(result);
        }
    }
}

4. Using Spring’s RestTemplate

RestTemplate It is a class in the Spring library used to access the REST API. It is based on  HttpMessageConverter the interface and can convert Java objects into request parameters or response content.

RestTemplate It also supports various HTTP request methods, request header customization, file upload and download and other operations.

Sample code:

public class HttpTemplate {

    public static String httpGet(String url) {
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.exchange(url, HttpMethod.GET, null, String.class).getBody();
        return result;
    }

    public static String httpPost(String url, String name) {
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForEntity(url, name, String.class).getBody();
    }

    public static void main(String str[]) {
        System.out.println(HttpTemplate.httpGet("https://www.example.com"));
        System.out.println(HttpTemplate.httpPost("https://www.example.com", "ming"));
    }
}

Note: In the above sample code, we did not consider the possibility of network request failure. In practical applications, exceptions need to be caught and handled.

Summarize

The above is what I will talk about today. This article only briefly introduces several common ways to send HTTP requests in Java. You can choose the appropriate method according to actual needs.

Guess you like

Origin blog.csdn.net/m0_71777195/article/details/132204088