简体   繁体   中英

How to set proxy header in HttpURLConnection

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. `

        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");`
        

You add headers in by calling setRequestProperty method:

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");`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM