java 如何在 HttpPost 中设置代理

How to set Proxy in HttpPost in java

请考虑我有一个带有字段的自定义代理 Class,

private final String serverName;
private final int port;
private final String username;
private final String password;

我想在下面的现有代码中使用此代理,但我不确定如何添加它。以下代码不支持代理。

public CustomClassForResponse createRequest(CreateCustomRequest request) {
        HttpPost httpRequest = new HttpPost();
        try {
            URIBuilder uriBuilder = new URIBuilder();
            uriBuilder.setScheme(URL_SCHEME).setHost(HOST_URL).setPath("/api");
            httpRequest.setURI(uriBuilder.build());
            httpRequest.setHeader("Authorization", accessToken());
            httpRequest.setHeader("Content-Type", "application/json");
            httpRequest.setHeader("Accept", "application/json");

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(1000 * 60 * 5)
                    .setSocketTimeout(1000 * 60 * 5)
                    .build();
            httpRequest.setConfig(requestConfig);

            httpRequest = (HttpPost) addJsonBody(request, httpRequest);

            return sendRequest(httpRequest, CustomClassForResponse.class);
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }
    
    private HttpEntityEnclosingRequest addJsonBody(JsonRequest request, HttpEntityEnclosingRequest httpRequest) throws JsonProcessingException {
        EntityBuilder builder = EntityBuilder.create();
        builder.setContentType(ContentType.APPLICATION_JSON);
        builder.setText(ObjectMapperProvider.getInstance().writeValueAsString(request));
        HttpEntity httpEntity = builder.build();
        httpRequest.setEntity(httpEntity);
        return httpRequest;
    }
    
    private <T extends JsonResponse> T sendRequest(HttpRequestBase httpRequest, Class<T> responseClass) throws IOException {
        CloseableHttpResponse response = createHttpClient().execute(httpRequest, createHttpClientContext());
        HttpEntity entity = response.getEntity();
        if (isResponseSuccess(response)) {
            T jsonResponse = ObjectMapperProvider.getInstance().readValue(entity.getContent(), responseClass);
            return jsonResponse;
        } else {
            throw new CustomException();
        }
    }

所以调用 createRequest 方法,然后调用 addJsonBody,然后调用 sendRequest 方法。

以下是版本详情:

("org.apache.httpcomponents:httpcore:4.4.6")
("org.apache.httpcomponents:httpclient:4.5.13")
("org.apache.httpcomponents:httpmime:4.5.3")
("commons-logging:commons-logging:1.2")

在创建客户端时设置代理,或者在请求时设置代理。

因为您已经引用了 createHttpClient() 方法:

private ClosableHttpClient createHttpClient() {
  HttpClientBuilder builder = HttpClients.custom();
  builder.setProxy(HttpHost.create("http://my.proxy"));
  return builder.build();
}

或在创建请求时设置它:

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(1000 * 60 * 5)
                    .setSocketTimeout(1000 * 60 * 5)
                    .setProxy("http://my.proxy")
                    .build();

既然你暗示它是一个经过身份验证的代理,那么我想一些凭证是正确的。

private ClosableHttpClient createHttpClient() {
  CredentialsProvider creds = new BasicCredentialsProvider();
  creds.setCredentials(new AuthScope("my.proxy", 80), 
     new UsernamePasswordCredentials("myuser", "mypassword")));
  HttpClientBuilder builder = HttpClients.custom()
     .setDefaultCredentialsProvider(creds)
     .setProxyAuthenticationStrategy(ProxyAuthenticationStrategy.INSTANCE)
     .setProxy(HttpHost.create("http://my.proxy"));
  return builder.build();
}