gpt4 book ai didi

java - 如何解决 Android 上的 HttpGet 问题?

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

我编写了在 Android 上发出 get 请求的代码,但出现如下错误:

07-07 21:12:39.674: E/AndroidRuntime(2409):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)

所以我读到我必须使用 AsyncTask。我做到了。有一次它运行良好,但下次我运行应用程序时,我又遇到了这个错误。

这是我的代码:

package app.teksty;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;



public class MainActivity extends Activity {


private class HttpGetRequest extends AsyncTask<String, Integer, Void>
{

private InputStream content;

@Override
protected Void doInBackground(String... params) {

String url = params[0];
Log.i("[GET REQUEST]", "STARTED");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.e("[GET REQUEST]", "Network exception", e);
}

return null;

}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);

BufferedReader r = new BufferedReader(new InputStreamReader(content));
StringBuilder respond = new StringBuilder();
String line;
try {

while ((line = r.readLine()) != null) {
respond.append(line);
}

Log.i("[GET REQUEST]", respond.toString());

} catch (IOException e) {

Log.e("[GET REQUEST]", "", e);
}

}


}


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

new HttpGetRequest().execute("http://www.google.pl");

setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}


}

我做错了什么或者我必须如何解决这个问题?

最佳答案

尝试将此代码放入您的方法onCreate()中:

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

但是,这仅适用于构建 sdk 版本 9 及更高版本

关于java - 如何解决 Android 上的 HttpGet 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11378712/

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