使用HttpURLConnection设置自定义标头

时间:2016-06-28 07:27:45

标签: java rest http-headers httpurlconnection urlconnection

我只是使用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();
}

我错过了什么?

2 个答案:

答案 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");

应更改类型值和标题。 它适用于我的情况。