可以使用Java中的HttpURLConnection类来发送HTTP请求。以下是一个示例代码,可以发送HTTP GET请求并设置请求头和查询参数:

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

public class HttpGetRequest {
    public static void main(String[] args) {
        try {
            // 设置请求地址和查询参数
            String url = "https://example.com/api";
            String query = "param1=value1&param2=value2";
            String fullUrl = url + "?" + query;

            // 创建URL对象和连接对象
            URL apiUrl = new URL(fullUrl);
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "Bearer your_access_token");

            // 发送GET请求
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();

            // 读取响应内容
            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 Code: " + responseCode);
            System.out.println("Response Body: " + response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,我们首先设置请求地址和查询参数,然后创建URL对象和HttpURLConnection对象。接着,我们设置请求头,包括Content-Type和Authorization等。最后,我们使用setRequestMethod()方法设置HTTP请求方法为GET,并发送请求。在获取响应内容后,我们可以输出响应状态码和响应体。注意要处理异常,例如连接超时或读取响应内容失败等

如何使用java发送http的get请求且要输入请求头和查询参数

原文地址: http://www.cveoy.top/t/topic/fjLK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录