Java - How to send HTTP request through proxy server
July 19, 2023
Here is a code to send HTTP request with proxy server using Apache HttpClient.
package com.example.demo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestAppApplication implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(TestAppApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(1,false);
HttpHost host = new HttpHost("149.129.131.46", 8080);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(30000)
.setConnectionRequestTimeout(30000)
.setSocketTimeout(30000)
.setProxy(host)
.build();
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config)
.setRetryHandler(retryHandler)
.build();
HttpGet getreq = new HttpGet("http://google.com");
CloseableHttpResponse response = client.execute(getreq);
System.out.println(response.getStatusLine().getStatusCode());
client.close();
}
}