我是Java的新手,我只是使用HttpURLConnection向Rest API发出GET请求。使用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();
}
我缺少什么?有什么建议么。
2016-06-28
Beginner
+0
这会返回您的值;的System.out.println(conn.getRequestProperty( “CustomHeader”)); –