Java HTTP请求头如何设置

发布时间:2025-04-27 15:57:55 作者:小樊
来源:亿速云 阅读:123

在Java中,可以使用HttpURLConnection类来发送HTTP请求并设置请求头。以下是一个简单的示例,展示了如何使用HttpURLConnection设置请求头:

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

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

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

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

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

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

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }

            // 关闭输入流
            in.close();

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

            // 断开连接
            connection.disconnect();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,我们设置了两个请求头:Content-TypeAuthorization。你可以根据需要添加其他请求头,只需使用connection.setRequestProperty(String key, String value)方法即可。

推荐阅读:
  1. java中HTTP请求流程是怎么样的
  2. Java中如何实现HttpServletResponse响应

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Java HTTP客户端如何提高性能

下一篇:Java HTTP协议中的错误处理

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》