I am trying to build an HTTP request to be sent via a proxy that accepts a proxy header. I am trying to find a way to set that, but couldn’t see it.
Below is the curl command which I need to convert to the Java code.
curl -i -u user:pwd -k GET –http1.1 –proxy-insecure https://localhost:8443 –proxy-header “X-Connect-Client-Id: abcde” https://target_host/api
This is what I was trying to do. `
JavaScript
x
Properties systemSettings = System.getProperties();
systemSettings.put("proxySet", "true");
systemSettings.put("http.proxyHost", "localhost");
systemSettings.put("http.proxyPort", "8443");
URL url = new URL("https://target_host/api");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
byte[] message = ("user:pwd").getBytes(StandardCharsets.UTF_8);
String basicAuth = DatatypeConverter.printBase64Binary(message);
con.setRequestProperty("Proxy-Authorization", "Basic " + basicAuth);
con.setRequestMethod("GET");`
Advertisement
Answer
You add headers in by calling setRequestProperty
method:
JavaScript
Properties systemSettings = System.getProperties();
systemSettings.put("proxySet", "true");
systemSettings.put("http.proxyHost", "localhost");
systemSettings.put("http.proxyPort", "8443");
URL url = new URL("https://target_host/api");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
byte[] message = ("user:pwd").getBytes(StandardCharsets.UTF_8);
String basicAuth = DatatypeConverter.printBase64Binary(message);
con.setRequestProperty("Proxy-Authorization", "Basic " + basicAuth);
con.setRequestProperty("X-Connect-Client-Id", "abcde");
con.setRequestMethod("GET");`