का उपयोग कर कस्टम हेडर सेट करना मैं जावा में नया हूं और मैं बस 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();
}
मैं क्या याद आ रही है? कोई सुझाव।
यह आपके मूल्य को लौटाता है; Println (conn.getRequestProperty ("CustomHeader")); – erolkaya84