2016-09-08 32 views
0

我正在尝试使用Java使用代理进行http请求,并获取整型变量中的响应代码。检查使用java通过代理进行的请求的状态代码

我使用的方法是:

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

回答

1

你可以试试这个:

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); 
相关问题