我正在尝试访问服务器,以便可以接收JSON字符串。但是显然在Ice Cream三明治中你不能在主线程中做网络操作,但是AsyncTask类把我搞糊涂了,而且不能工作。这是我到目前为止所知道的:
//up in main code
Void blah = null;
URI uri = "kubie.dyndns-home.com/R2Bar2/ingredients.php";
new DownloadFilesTask().execute(uri , blah, blah);
private class DownloadFilesTask extends AsyncTask<URI, Void, Void> {
protected Void doInBackground(URI... uri) {
HttpClient client = new DefaultHttpClient();
String json = "";
int duration = Toast.LENGTH_SHORT;
try {
HttpResponse response = null;
BufferedReader rd = null;
String line = "";
HttpGet request = new HttpGet(uri);
} catch (URISyntaxException e1) {
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}它不喜欢我的HttpGet request = new HttpGet(uri),它说要将uri更改为URI,但它已经这样做了!我尝试将所有参数更改为Void,但我的应用程序只是强制关闭。
有人知道怎么做吗?
发布于 2012-03-16 08:21:33
试一下这个例子:
public class Test_anroidActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String uri = new String("http://kubie.dyndns-home.com/R2Bar2/ingredients.php");
new DownloadFilesTask().execute(uri , null, null);
}
private class DownloadFilesTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
HttpClient client = new DefaultHttpClient();
String json = "";
try {
String line = "";
HttpGet request = new HttpGet(urls[0]);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = rd.readLine()) != null) {
json += line + System.getProperty("line.separator");
}
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
return json;
}
protected void onProgressUpdate(Void... progress) {
}
protected void onPostExecute(String result) {
}
}
}最后一个,你的服务器返回php文件,这是正确的行为吗?
发布于 2012-03-16 07:52:59
,但显然在Ice Cream三明治中,你不能在主线程中进行网络操作
您可以,但它会在LogCat中给您一个警告。您不应该在主应用程序线程上执行网络操作,因为它会冻结您的UI,并可能出现"Application not Responding“(ANR)对话框。
,但是AsyncTask类把我搞糊涂了,而且不能工作
在您当前的代码中,您实际上并没有执行HttpGet请求。
它不喜欢我的HttpGet request =
HttpGet( uri ),它说要将URI改为URI,但它已经这样做了!
不,它不是。
doInBackground()声明中URI之后的...表示此方法接受数量可变的参数。实际上,您的uri参数是一个URI[]。如果您只使用一个URI调用execute(),则可以通过uri[0]而不是uri访问该URI。
https://stackoverflow.com/questions/9729825
复制相似问题