java httpclient proxy example

Solutions on MaxInterview for java httpclient proxy example by the best coders in the world

showing results for - "java httpclient proxy example"
Ewenn
28 Jun 2016
1import org.apache.http.HttpHost;
2import org.apache.http.HttpResponse;
3import org.apache.http.auth.AuthScope;
4import org.apache.http.auth.UsernamePasswordCredentials;
5import org.apache.http.client.CredentialsProvider;
6import org.apache.http.client.config.RequestConfig;
7import org.apache.http.client.methods.HttpGet;
8import org.apache.http.impl.client.BasicCredentialsProvider;
9import org.apache.http.impl.client.CloseableHttpClient;
10import org.apache.http.impl.client.HttpClientBuilder;
11import org.apache.http.impl.client.HttpClients;
12
13public class ProxyAuthenticationExample {
14   public static void main(String[] args) throws Exception {
15
16      //Creating the CredentialsProvider object
17      CredentialsProvider credsProvider = new BasicCredentialsProvider();
18
19      //Setting the credentials
20      credsProvider.setCredentials(new AuthScope("example.com", 80), 
21         new UsernamePasswordCredentials("user", "mypass"));
22      credsProvider.setCredentials(new AuthScope("localhost", 8000), 
23         new UsernamePasswordCredentials("abc", "passwd"));
24
25      //Creating the HttpClientBuilder
26      HttpClientBuilder clientbuilder = HttpClients.custom();
27
28      //Setting the credentials
29      clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);
30      
31      //Building the CloseableHttpClient object
32      CloseableHttpClient httpclient = clientbuilder.build();
33
34
35      //Create the target and proxy hosts
36      HttpHost targetHost = new HttpHost("example.com", 80, "http");
37      HttpHost proxyHost = new HttpHost("localhost", 8000, "http");
38
39      //Setting the proxy
40      RequestConfig.Builder reqconfigconbuilder= RequestConfig.custom();
41      reqconfigconbuilder = reqconfigconbuilder.setProxy(proxyHost);
42      RequestConfig config = reqconfigconbuilder.build();
43
44      //Create the HttpGet request object
45      HttpGet httpget = new HttpGet("/");
46
47      //Setting the config to the request
48      httpget.setConfig(config);
49 
50      //Printing the status line
51      HttpResponse response = httpclient.execute(targetHost, httpget);
52      System.out.println(response.getStatusLine());
53
54   }
55}