我怀疑我在简单的Android应用中遇到了线程问题。
我有一个活动,它执行以下操作:
DefaultHttpClient
检索数据并关闭此连接。这成功地将URL返回到互联网上的图片HttpUrlConnection
的{{1}}并尝试使用conn.connect 不确定要放在哪里的代码,我可以将其全部粘贴,但这样会太多,所以如果需要更多信息请告诉我:
conn
答案 0 :(得分:3)
首先确保您为展示添加了互联网权限:
<uses-permission android:name="android.permission.INTERNET" />
在AndroidManifest.xml中的应用程序代码之外
将} catch (IOException e) {
更改为} catch (Exception e) {
如果一切顺利,请尝试以下代码:
System.setProperty("http.keepAlive", "false");
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setUseCaches(false);
conn.setConnectTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
//conn.connect(); // You are allready connected after openConnection().
如果仍然没有运气,请尝试使用HttpClient
&amp; HttpGet
这样:
final HttpClient client = new DefaultHttpClient();
final HttpGet conn = new HttpGet(myFileUrl.toString());
HttpResponse response = client.execute(conn);
InputStream is = response.getEntity().getContent();
答案 1 :(得分:0)
我至少将连接和读取超时都放在,例如
conn.setConnectTimeout(5000); conn.setReadTimeout(5000);
答案 2 :(得分:0)
我遇到了完全相同的问题,这使我疯狂地解决了问题。我已经在设置timout参数,但是httpurlconnection挂在connect()调用上,或者稍后在getInputStream()上挂起,如果我没有明确调用connect()。
使用原始线程代替asynctask对我有用,而无需更改其他任何内容...
new Thread(() -> task.doInBackground())
解决方案多于解决方案,但总比没有好。
答案 3 :(得分:-1)
删除这两行:
conn.setDoInput(true);
conn.connect(); // freezes here
执行此操作时:
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
int length = conn.getContentLength();
您已连接。调用conn.getContentLength()
会导致HttpURLConnection
建立连接,发送请求并获取响应。您不需要显式连接。您也无需致电setDoInput(true)
,因为这是默认设置。