我知道这个问题已被问过好几次,但我现在很无奈。
我在localhost上有一个回显“Hello”的php网页。 (在localhost工作完美)。 我有以下代码,显示从我的应用程序中localhost网页到TextView的响应。
tv = (TextView) findViewById(R.id.txtTest);
InputStream is = null;
String result = "";
String url = "http://10.0.2.2/android/try.php";
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
Log.d("myapp", "response " + response.getEntity());
HttpEntity entity = response.getEntity();
is = entity.getContent();
String st = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
tv.setText(result.toString());
我收到以下错误(LogCat)。
09-24 13:34:42.654: E/log_tag(2032): Error in http connection android.os.NetworkOnMainThreadException
09-24 13:34:42.654: E/log_tag(2032): Error converting result java.lang.NullPointerException
P.S 我在Manifest中添加了Internet权限。
答案 0 :(得分:3)
您应该从与主(UI)线程不同的线程执行网络操作(连接等)。这就是你得到的错误android.os.NetworkOnMainThreadException
意味着什么。
您应该查看ASyncTask或Thread来执行此操作。
同时阅读this article ...
将目前的代码替换为:
AsyncTask<Void,Void,Void> my_task = new AsyncTask<Void,Void,Void>() {
@Override
protected void onPostExecute() {
TextView tv = (TextView) findViewById(R.id.txtTest);
tv.setText(result.toString());
}
@Override
protected Void doInBackground(Void... voids) {
InputStream is = null;
String result = "";
String url = "http://10.0.2.2/android/try.php";
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
Log.d("myapp", "response " + response.getEntity());
HttpEntity entity = response.getEntity();
is = entity.getContent();
String st = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}
}.execute();