[JavaSE Column 91] How does Java actively initiate Http and Https requests?

Author homepage : Designer Xiao Zheng
Author brief introduction : 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, dedicated to enterprise digital transformation, certified lecturer of CSDN College and Blue Bridge Cloud Course.
Main direction : Vue, SpringBoot, WeChat applet

This article explains how to use Java to initiate HTTP requests and gives sample code. HTTP is a protocol used to transmit data between Web browsers and Web servers. Java can initiate HTTP requests through third-party tool classes.

Insert image description here


1. What are http and https?

HTTP is a protocol used to transfer data between a web browser and a web server.

HTTP is a stateless, connection-oriented protocol that uses TCP as the transport protocol and runs at 80 80 by default.on port 80 . HTTP usage请求-响应model, the client sends an HTTP request to the server, and the server returns the corresponding HTTP response according to the request.

HTTPS is an encrypted HTTP protocol. It encrypts HTTP communications using SSL or TLS protocols to ensure data security during transmission.

HTTPS adds encryption and authentication functions to HTTP, making data more secure and reliable during transmission .

When the client initiates an HTTPS request, the server returns a public key certificate, and the client uses the server's public key to encrypt the communication.

During the communication process, the server uses the private key to decrypt the data sent by the client, and the client uses the server's public key to encrypt the data sent.

In this way, even if someone intercepts the communication data, the content cannot be decrypted, thus protecting the confidentiality and integrity of the data.

HTTPS is commonly used on websites that need to protect the transmission of sensitive information , such as banking, e-commerce, and social media.

By using HTTPS, network attacks such as eavesdropping, tampering, and disguise can be effectively prevented, and the security of data transmission is improved.

Insert image description here


2. How to initiate an http request

Java can use java.net.HttpURLConnectionor third-party libraries (such as Apache HttpClient, OkHttpetc.) to initiate HTTP requests. The following is a sample code that uses to java.net.HttpURLConnectioninitiate HTTP requests. Please copy it to local execution.GET

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpExample {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            // 创建URL对象
            URL url = new URL("http://api.example.com/data"); // 替换为实际的URL

            // 打开HTTP连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为GET
            connection.setRequestMethod("GET");

            // 获取响应状态码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 读取响应内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
    
    
                response.append(line);
            }
            reader.close();

            // 打印响应内容
            System.out.println("Response Body: " + response.toString());

            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

In this example, we first create a URL object, specifying the URL to request.

We then url.openConnection()open the HTTP connection via and cast it to HttpURLConnectionan object.

Then, we can set the request method (such as GET, POSTetc.), get the response status code, read the response content and process it accordingly, and finally we close the connection.

Actual HTTP requests may need to process more request headers, request bodies, response headers and other information. Using third-party libraries can provide more functions and convenience.

Insert image description here


3. How to initiate https request

In Java, you can use HttpsURLConnectionthe class to initiate HTTPS requests. The following is a sample code that uses to HttpsURLConnectioninitiate a request. Please copy it to local execution.GET

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;

public class HttpsExample {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            // 创建信任管理器
            TrustManager[] trustAllCerts = new TrustManager[] {
    
     new X509TrustManager() {
    
    
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
    
    }
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
    
    }
                public X509Certificate[] getAcceptedIssuers() {
    
     return null; }
            }};
            
            // 获取默认的SSL上下文
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            
            // 创建URL对象
            URL url = new URL("https://api.example.com/data"); // 替换为实际的URL
            
            // 打开HTTPS连接
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            
            // 设置请求方法为GET
            connection.setRequestMethod("GET");
            
            // 获取响应状态码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            
            // 读取响应内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
    
    
                response.append(line);
            }
            reader.close();
            
            // 打印响应内容
            System.out.println("Response Body: " + response.toString());
            
            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

We create a trust manager that implements the operation of trusting all certificates.

We then get the default SSL context and apply the trust manager to that SSL context.

Next, we create the URL object and url.openConnection()open the HTTPS connection using and cast it to HttpsURLConnectionthe object.

Then, we can set the request method (such as GET, POSTetc.), get the response status code, read the response content and process it accordingly, and finally we close the connection.

The operation of trusting all certificates in this sample code is not safe and is only suitable for testing or development environments. In a production environment, it is recommended that students use real certificates and trusted certificate chains for verification.

Insert image description here


4. Status code and data analysis of http request

You can use Java HttpURLConnectionor a third-party library to initiate HTTP requests and obtain the response status code and data.

First, to initiate an HTTP request and obtain the response status code, you can use the following code. Please copy it and execute it locally.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpExample {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            // 创建URL对象
            URL url = new URL("http://api.example.com/data");

            // 打开HTTP连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            // 设置请求方法为GET
            connection.setRequestMethod("GET");
            
            // 获取响应状态码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            
            // 读取响应内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
    
    
                response.append(line);
            }
            reader.close();
            
            // 打印响应内容
            System.out.println("Response Body: " + response.toString());
            
            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

The above code creates URLan object, url.openConnection()opens an HTTP connection using , and then sets the request method to GET.

Then, connection.getResponseCode()get the status code of the response through , connection.getInputStream()get the input stream of the response through , and BufferedReaderread the response content line by line using , and finally print the response content and close the connection.

Then, regarding data parsing, how to parse the response data depends on the format of the data (such as JSON, XML, HTML, etc.) and the library used.

Commonly used data parsing libraries include: JSONObjectand JSONArray(processing JSON data), SAXParserand DOMParser(processing XML data), Jsoup(processing HTML data), and of course there are many other third-party libraries to choose from.

Here we take the use of JSONObjectparsing JSON data as an example to give students a reference.

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonExample {
    
    
    public static void main(String[] args) {
    
    
        String jsonData = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

        try {
    
    
            JSONObject jsonObject = new JSONObject(jsonData);
            String name = jsonObject.getString("name");
            int age = jsonObject.getInt("age");
            String city = jsonObject.getString("city");

            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("City: " + city);
        } catch (JSONException e) {
    
    
            e.printStackTrace();
        }
    }
}

The above code parses a JSON string JSONObjectand then obtains the value of the corresponding field through methods such as getString(key)and .getInt(key)

Insert image description here


5. http request interview questions

  1. Please explain how HTTP request works in Java?
  2. Please introduce the classes and libraries commonly used in Java to send HTTP requests.
  3. What are the common HTTP request methods? Please give their meaning and usage.
  4. How to send a GET request in Java? Please give sample code.
  5. How to send a POST request in Java? Please give sample code.
  6. How to handle responses to HTTP requests? How to get the status code and data of the response?
  7. Please explain the HTTP status codes. What are the common status codes and what do they mean?
  8. How to handle HTTP request exceptions and errors in Java?
  9. How to set the request headers and request parameters of an HTTP request?
  10. How to handle timeouts and retries of HTTP requests in Java?

6. Summary

This article explains how to use Java to initiate HTTP requests and gives sample code, 91 9191 Java SE introductory tutorials have been released.

Insert image description here

Guess you like

Origin blog.csdn.net/qq_41464123/article/details/132570383