【问题标题】:Setting custom header using HttpURLConnection使用 HttpURLConnection 设置自定义标头
【发布时间】: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


【解决方案1】:

发送是个好主意

conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("CustomHeader", token);

而不是

// Set Headers
conn.setRequestProperty("CustomHeader", "someValue");
conn.setRequestProperty("accept", "application/json");

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

【讨论】:

  • 这是一个GET 请求。我没有发送任何内容并期待application/json 类型的响应所以,有什么理由在这里使用Content-Type 而不是accept?
  • 谁自己将“header”重命名为“property”?这非常令人惊讶。
【解决方案2】:

conn.getHeaderField("CustomHeader") 返回的是 response 头而不是请求头。

要返回请求标头,请使用:conn.getRequestProperty("CustomHeader")

【讨论】:

  • 是的,它返回了那个。谢谢 :) 不知道为什么要得到 401。
猜你喜欢
  • 2018-12-17
  • 2016-08-28
  • 1970-01-01
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 2014-02-21
相关资源
最近更新 更多