2016-06-28 13 views
6

का उपयोग कर कस्टम हेडर सेट करना मैं जावा में नया हूं और मैं बस HttpURLConnection का उपयोग कर एक बाकी एपीआई के लिए अनुरोध कर रहा हूं।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

यह आपके मूल्य को लौटाता है; 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' अनुरोध है। मैं कोई सामग्री नहीं भेज रहा हूं और टाइप 'एप्लिकेशन/जेसन' की प्रतिक्रिया की उम्मीद कर रहा हूं, तो क्या यहां 'स्वीकृति' के बजाय 'सामग्री-प्रकार' का उपयोग करने का कोई कारण है? – Beginner

संबंधित मुद्दे