2016-06-28 4 views
6

私はJavaを初めて使用しており、HttpURLConnectionを使用して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(); 
} 

私は何をしないのですか?助言がありますか。

+0

これはあなたの価値を返します。 System.out.println(conn.getRequestProperty( "CustomHeader")); – erolkaya84

答えて

4

conn.getHeaderField("CustomHeader")は、応答ヘッダーを要求したものではなく返します。リクエストヘッダの使用を返すように

conn.getRequestProperty("CustomHeader")

+0

ええ、それが返されました。ありがとう:) 401を取得する理由はわかりません。 – Beginner

4

タイプ値とヘッダの両方が変更されなければならない代わり

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

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

を送信することをお勧めします。 それは私の場合に動作します。

+1

これは 'GET'リクエストです。私はコンテンツを送信せず、 'application/json'型の応答を期待していますので、ここで' accept'の代わりに 'Content-Type'を使う理由がありますか? – Beginner

関連する問題