gpt4 book ai didi

java - 如何在Java中的GET方法的HttpRequest中添加 header

转载 作者:行者123 更新时间:2023-11-30 03:30:50 27 4
gpt4 key购买 nike

我必须传递一个 token 作为每个 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()也有效

关于java - 如何在Java中的GET方法的HttpRequest中添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29098500/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com