Java 使用 HttpURLConnection 设置自定义标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38069719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting custom header using HttpURLConnection
提问by Beginner
I am simply making a GET
request to a Rest API using HttpURLConnection
.
我只是GET
使用HttpURLConnection
.
I need to add some custom headers but I am getting null
while trying to retrieve their values.
我需要添加一些自定义标头,但null
在尝试检索它们的值时却遇到了问题。
Code:
代码:
URL url;
try {
url = new URL("http://www.example.com/rest/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set Headers
conn.setRequestProperty("CustomHeader", "someValue");
conn.setRequestProperty("accept", "application/json");
// Output is null here <--------
System.out.println(conn.getHeaderField("CustomHeader"));
// Request not successful
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Request Failed. HTTP Error Code: " + conn.getResponseCode());
}
// Read response
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
What am I missing?
我错过了什么?
采纳答案by Krzysztof Krasoń
The conn.getHeaderField("CustomHeader")
returns the responseheader not the request one.
在conn.getHeaderField("CustomHeader")
返回响应标头而不是请求之一。
To return the request header use: conn.getRequestProperty("CustomHeader")
要返回请求标头,请使用: conn.getRequestProperty("CustomHeader")
回答by Alp Altunel
It is a good idea to send
发送是个好主意
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("CustomHeader", token);
instead of
代替
// Set Headers
conn.setRequestProperty("CustomHeader", "someValue");
conn.setRequestProperty("accept", "application/json");
Both the type value and header should be changed. it works in my case.
类型值和标题都应该更改。它适用于我的情况。