我只是使用GET
向Rest API发出HttpURLConnection
请求。
我需要添加一些自定义标题,但在尝试检索其值时我收到null
。
代码:
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();
}
我错过了什么?
答案 0 :(得分:5)
conn.getHeaderField("CustomHeader")
会返回响应标头而非请求标头。
要返回请求标头,请使用:conn.getRequestProperty("CustomHeader")
答案 1 :(得分:5)
发送
是个好主意conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("CustomHeader", token);
而不是
// Set Headers
conn.setRequestProperty("CustomHeader", "someValue");
conn.setRequestProperty("accept", "application/json");
应更改类型值和标题。 它适用于我的情况。