【发布时间】:2016-06-28 07:27:44
【问题描述】:
我只是使用HttpURLConnection 向Rest API 发出GET 请求。
我需要添加一些自定义标头,但我在尝试检索它们的值时收到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();
}
我错过了什么?
【问题讨论】:
-
这会返回你的值; System.out.println(conn.getRequestProperty("CustomHeader"));
标签: java rest http-headers httpurlconnection urlconnection