[英]Check status code for a request made via proxy using java
我正在尝试使用Java使用代理发出http请求,并在整数变量中获取响应代码。
我使用的方法是:
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;
}
我正在传递代理参数,但不确定在发出请求时如何使用它。 我试图在线查找资源,但找不到合适的解决方案。
我尝试了以下解决方案,但不确定如何在此处获取响应代码:
HttpHost proxy = new HttpHost("proxy.com", 80, "http");
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
您可以尝试以下方法:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.