[英]class to read http pages with reliable timout that return `java.io.InputStream`
是否有用於讀取返回java.io.InputStream
及其超時的http頁面的類?
我嘗試過java.net.URLConnection
並且它沒有可靠的超時(設置為超時范圍需要更多時間)? 我的代碼在這里:
URLConnection con = url.openConnection();
con.setConnectTimeout(2000);
con.setReadTimeout(2000);
InputStream in = con.getInputStream();
我希望超時不起作用的原因是你在建立連接后設置了超時,或者你使用了錯誤的setter。 您也可能使用的是URLConnection的“非標准”版本...
“此方法的某些非標准實現會忽略指定的超時。要查看讀取超時設置,請調用
getReadTimeout()
。” (或getConnectTimeout()
)
如果您發布了實際代碼的相關部分,我們可以為您提供更好的答案...
或者,使用Apache HttpClient庫。
您可以使用Apache HttpClient來讀取http頁面,它也具有http解析器。請檢查此內容以獲取有關httpclient的更多參考 。 你可以像這樣使用他們的API來獲取一個InputStream對象。
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet("http://www.apache.org/");
// Execute the request
HttpResponse response = httpclient.execute(httpget);
// Examine the response status
System.out.println(response.getStatusLine());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
InputStream instream = entity.getContent();
並且到了超時部分,它完全取決於網絡,你不能從你的java代碼做很多事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.