2012-09-04 60 views
3

我有一些Java代碼是從前一個同事繼承的。它的一部分使用方法GET連接到外部URL,並檢索少量的XML進行分析。由於供應商網站被掛起並使用了我們的資源,我們最近因這種連接導致我們的網站崩潰而一直有問題。有一個問題是由於我們的代碼使用HttpGet對象時沒有設置超時。有沒有辦法使用這個對象來微調超時,還是有更好的方法來撤回這個XML?通過HttpGet對象檢索數據時設置超時值

使用其他API會更好嗎?

List<NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("param1","foobar")); 
URI uri = URIUtils.createURI("http", "myhost.com", -1, "mypath", 
URLEncodedUtils.format(params, "UTF-8"), null); 

// there is no timeout here?? 
HttpGet httpGet = new HttpGet(uri); 
HttpClient httpClient = new DefaultHttpClient(); 
HttpResponse httpResponse = httpClient.execute(httpGet); 
String result = IOUtils.toString(httpResponse.getEntity() 
    .getContent(), "UTF-8"); 

謝謝!

+0

可能重複:http://stackoverflow.com/questions/3000214/java-http-client-request-with-defined-timeout –

回答

6

試試這個,而不是

List<NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("param1","foobar")); 
URI uri = URIUtils.createURI("http", "myhost.com", -1, "mypath", 
URLEncodedUtils.format(params, "UTF-8"), null); 

HttpGet httpGet = new HttpGet(uri); 
HttpClient httpClient = new DefaultHttpClient(); 
// set the connection timeout value to 30 seconds (30000 milliseconds) 
final HttpParams httpParams = new BasicHttpParams(); 
HttpConnectionParams.setConnectionTimeout(httpParams, 30000); 
httpClient = new DefaultHttpClient(httpParams); 
HttpResponse httpResponse = httpClient.execute(httpGet); 
String result = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"); 

Java HTTP Client Request with defined timeout

+0

謝謝 - 這很好用! – acvcu