2016-06-28 549 views
6

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

我缺少什么?有什么建议么。

+0

这会返回您的值;的System.out.println(conn.getRequestProperty( “CustomHeader”)); – erolkaya84

回答

4

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

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

+0

是的,它回来了。谢谢:) 不知道为什么得到401. – Beginner

4

这是一个好主意,派而不是

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

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

两种类型的值和标题应该改变。 它适用于我的情况。

+1

这是一个'GET'请求。我没有发送任何内容并期待'application/json'类型的响应,因此,在这里有没有任何理由使用Content-Type而不是'accept'? – Beginner