如何向HttpClient添加代理选项?

时间:2018-01-26 18:24:39

标签: java proxy request httpclient

我注意到使用

时不会使用HttpClient选择代理设置
-Dhttp.proxyHost=127.0.0.1 and -Dhttp.proxyPort=8080

我的服务器上存在代理问题,运行我的代码会让我回来

org.apache.http.conn.HttpHostConnectException: Connection timed out (Connection timed out)

因此,当我在本地计算机上运行时,以下代码会返回URL的响应,但是当我在服务器上运行时,则不会。因为它没有从类路径中获取ProxyURL和proxyPort,所以我打算手动检索它们(我将从配置文件中读出它们),但我不确定在哪里将这两个值添加到请求对象中,确切地说,一旦我拥有它们?

public String sendPost(String url) {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    StringBuffer result = new StringBuffer();

    try {
        HttpPost post = new HttpPost(url);
        post.setHeader("User-Agent", USER_AGENT);

        HttpResponse response = null;
        BufferedReader rd = null;

        response = client.execute(post);

        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (Exception ex) {
       System.out.println(""+ex);
    }

    return result.toString();
}

0 个答案:

没有答案