Adding Header for Httpurlconnection

Adding header for HttpURLConnection

I have used the following code in the past and it had worked with basic authentication enabled in TomCat:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();

String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));

myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);

You can try the above code. The code above is for POST, and you can modify it for GET

Setting custom header using HttpURLConnection

The conn.getHeaderField("CustomHeader") returns the response header not the request one.

To return the request header use: conn.getRequestProperty("CustomHeader")

send header value using HttpUrlConnection

Try this one

URL url = new URL(strings[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
String token = "" + new String(accessToken);
con.setRequestMethod("GET");
con.setRequestProperty("AuthToken", token);
con.setReadTimeout(15000);
con.setConnectTimeout(15000);
con.setDoOutput(false);

Set http header using httpurlconnection

Here's the solution:

 BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

How to modify the header of a HttpUrlConnection

Open the URL with URL.openConnection. Optionally cast to HttpURLConnection. Call URLConnection.setRequestProperty/addRequestProperty.

The default User-Agent header value is set from the "http.agent" system property. The PlugIn and WebStart allow you to set this property.

HttpURLConnection GET request with http-header Accept

I can't see what programming language you're talking about, so I assume it's Java since this is the first thing that pops up when searching for httpURLConnection.

If that's the case, then you can write

URL url = new URL("https://stackoverflow.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
...
} finally {
urlConnection.disconnect();
}

Source



Related Topics



Leave a reply



Submit