简体   繁体   English

如何在HttpURLConnection中设置代理header

[英]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.我正在尝试构建一个 HTTP 请求,通过接受代理 header 的代理发送。我正在尝试找到一种方法来设置它,但看不到它。

Below is the curl command which I need to convert to the Java code.下面是 curl 命令,我需要将其转换为 Java 代码。

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 curl -i -u user:pwd -k GET --http1.1 --proxy-insecure https://localhost:8443 --proxy-header "X-Connect-Client-Id: abcde" https://target_host/应用程序接口

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:您可以通过调用setRequestProperty方法添加标头:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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