Pratim Singha
Pratim Singha

Reputation: 679

How to set Proxy in HttpPost in java

Please consider that I have a Custom Proxy Class with fields,

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

I want to use this Proxy in the below existing code, but I am not sure how to add that. The below code does not support proxy.

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();
        }
    }

so the createRequest method is called and then it calls the addJsonBody and then the sendRequest method.

Here are the version details:

("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")

Upvotes: 0

Views: 812

Answers (1)

quotidian-ennui
quotidian-ennui

Reputation: 126

Set the proxy when you create the client, or set the proxy on the Request.

Since you already refer to a createHttpClient() method :

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

or setting it when you create the request :

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

Since you're implying that it's an authenticated proxy then I guess some credentials are in order.

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();
}

Upvotes: 1

Related Questions