2016-06-28 553 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