Adding header for HttpURLConnection
To add a header to an HTTP request using HttpURLConnection
, you can use the setRequestProperty
method. This method takes a string key and a string value, and adds a new header to the request with the specified key and value. Here's an example of how you can use setRequestProperty
to add a "Content-Type" header to an HTTP request:
URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
You can also add multiple headers to the same request by calling setRequestProperty
multiple times.
connection.setRequestProperty("Header1", "value1");
connection.setRequestProperty("Header2", "value2");