我知道这个问题已经被问了好几次了,但现在我很无助。
我在 localhost 上有一个 php 网页,它回应了"你好"。(在本地主机工作完美)。 我有以下代码,在我的应用程序中显示从本地主机网页到 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());
我收到以下错误(日志猫)。
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
附言我在清单中添加了互联网权限。
您应该从与主 (UI) 线程不同的线程执行网络操作(连接等)。这就是您得到的错误android.os.NetworkOnMainThreadException
的意思。
您应该查看ASyncTask或Thread来执行此操作。
也阅读这篇文章...
将您当前的代码替换为以下内容:
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();