使用HttpURLConnection设置自定义标头

使用HttpURLConnection设置自定义标头

本文介绍了使用HttpURLConnection设置自定义标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是使用 HttpURLConnection 向Rest API发出 GET 请求。

I am simply making a GET request to a Rest API using HttpURLConnection.

我需要添加一些自定义标题,但在尝试检索其值时,我得到 null

I need to add some custom headers but I am getting null while trying to retrieve their values.

代码:

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();
}

我缺少什么?

推荐答案

conn.getHeaderField(CustomHeader)返回响应标头而不是请求一个。

The conn.getHeaderField("CustomHeader") returns the response header not the request one.

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

To return the request header use: conn.getRequestProperty("CustomHeader")

这篇关于使用HttpURLConnection设置自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 10:59