Reputation: 1411
I am trying to make an http request with proxy using Java and get the response code in an integer variable.
The method I am using is:
public static int getResponseCode(String urlString, Proxy p) throws MalformedURLException, IOException{
URL url = new URL(urlString);
HttpResponse urlresp = new DefaultHttpClient().execute(new HttpGet(urlString));
int resp_Code = urlresp.getStatusLine().getStatusCode();
return resp_Code;
}
I am passing a proxy parameter but I am not sure how to use it while making the request. I tried to look up resources online but was unable to find an apt solution.
I tried the below solution but was unsure how to get the response code here:
HttpHost proxy = new HttpHost("proxy.com", 80, "http");
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
Upvotes: 0
Views: 813
Reputation: 821
You could try this:
URL url = new URL("http://www.myurl.com");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.com", 8080));
// IF NEED AUTH
// Authenticator authenticator = new Authenticator() {
// public PasswordAuthentication getPasswordAuthentication() {
// return (new PasswordAuthentication("username",
// "password".toCharArray()));
// }
// };
// Authenticator.setDefault(authenticator);
HttpURLConnection conn = (HttpURLConnection)url.openConnection(proxy);
conn.setRequestMethod("GET");
conn.connect();
int code = conn.getResponseCode();
System.out.println(code);
Upvotes: 1