如何将header添加到Java中GET方法的HttpRequest

How to add header to HttpRequest of GET method in Java

我必须传递一个令牌作为每个 GET 请求验证的一部分才能访问 RESTful Web 服务。下面是我用来访问 REST api:

的代码
public static String httpGet(String urlStr, String[] paramName, String[] paramVal) throws Exception {
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

        OutputStream out = conn.getOutputStream();
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        for (int i = 0; i < paramName.length; i++) {
            writer.write(paramName[i]);
            writer.write("=");
            writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
            writer.write("&");
        }
        writer.close();
        out.close();

        if (conn.getResponseCode() != 200) {
            System.out.println("Response code: "+conn.getResponseCode());
            throw new IOException(conn.getResponseMessage());
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();

        conn.disconnect();
        return sb.toString();
    }

我看不到为 HttpsURLConnection 提供的任何此类设置 Header conn.setHeader() 的方法。它应该像 X-Cookie: token={token}; 请帮我想办法设置 header.

您可以使用:

conn.addRequestProperty("X-Cookie", "token={token}");

setRequestProperty()也有效

当您执行以下操作时,您已经在您的代码中根据您的请求设置了 headers:

    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

即如果您正在与之通信的服务要求您在 "X-Cookie" header 中发送您的令牌,您可以简单地为 header:

做同样的事情
conn.setRequestProperty("X-Cookie", "token={token}");