gpt4 book ai didi

java - http获取android异步任务

转载 作者:行者123 更新时间:2023-12-01 12:24:21 25 4
gpt4 key购买 nike

当我实现这个时,它显示“NetworkOnMainThreadException”。

有人可以发布一个有效的示例吗?

我尝试了许多不同的示例和库,但没有成功。我的代码:

private class HttpGetter extends AsyncTask<URL, Void, Void> {

@Override
protected Void doInBackground(URL... urls) {
// TODO Auto-generated method stub
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(String.valueOf(urls[0]));

try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.v("Getter", "Your data: " + builder.toString()); //response data
} else {
Log.e("Getter", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}


}

最佳答案

你如何调用这个类对象。如果你这样调用那么你不应该得到这个异常。

new HttpGetter().excute(new URL("http://www.urlstring.com"));

或者,您可以毫无异常(exception)地使用以下代码运行您的代码,但不推荐

StrictMode.ThreadPolicy policy = new      StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy);

在 android manifest.xml 文件中添加此权限:

<uses-permission android:name="android.permission.INTERNET"/>

关于java - http获取android异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26468409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com