Sunday 3 September 2017

Adding headers using HttpURLConnection

HttpURLConnection class provides 'setRequestProperty' method to set the headers.

Below step-by-step procedure explains how to set headers.

Step 1: Get HttpURLConnection object
                 URL url = new URL(urlToConnect);
                 HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();

Step 2: Add headers to the HttpURLConnection using setRequestProperty method.
                 Map<String, String> headers = new HashMap<>();

                 headers.put("X-CSRF-Token", "fetch");
                 headers.put("content-type", "application/json");
                
                 for (String headerKey : headers.keySet()) {
                          httpUrlConnection.setRequestProperty(headerKey, headers.get(headerKey));
                 }
                
Find below working application.

Test.java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class Test {

 private static HttpURLConnection getURLConnection(String urlToConnect) throws IOException {
  URL url = new URL(urlToConnect);
  HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
  return httpUrlConnection;
 }

 private static void setHeaders(HttpURLConnection httpUrlConnection, Map<String, String> headers) {
  for (String headerKey : headers.keySet()) {
   httpUrlConnection.setRequestProperty(headerKey, headers.get(headerKey));
  }
 }

 public static void main(String[] args) throws IOException {
  String url = "urlToConnect";
  HttpURLConnection httpUrlConnection = getURLConnection(url);

  Map<String, String> headers = new HashMap<>();

  headers.put("X-CSRF-Token", "fetch");
  headers.put("content-type", "application/json");

  setHeaders(httpUrlConnection, headers);
  httpUrlConnection.getContent();

 }

}



Previous                                                 Next                                                 Home

No comments:

Post a Comment