我查看了一些论坛帖子,但找不到我的问题的答案。我正在尝试从 php 文件获取响应。 php 文件正在运行。问题是 Android 应用程序不会执行我的请求。以下是我的代码的两个示例以及我在文本视图中得到的结果:
public void changText(View view) {
TextView textv = (TextView)findViewById(R.id.textview1);
textv.setText("Text Has Been Changed");
BufferedReader in = null;
String data = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website = new URI("http://alanhardin.comyr.com/matt24/matt28.php");
request.setURI(website);
HttpResponse response = httpclient.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
textv.append(" Connected ");
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
TextView 显示:文本已更改
public void changText(View view) {
TextView textv = (TextView)findViewById(R.id.textview1);
textv.setText("Text Has Been Changed");
BufferedReader in = null;
String data = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website = new URI("http://alanhardin.comyr.com/matt24/matt28.php");
request.setURI(website);
//HttpResponse response = httpclient.execute(request);
//in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
textv.append(" Connected ");
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
TextView 显示:文本已更改已连接
在这个清单中我有:
<uses-permission android:name="android.permission.INTERNET" />
在错误日志中我得到以下内容:
http连接时出错 android.os.NetworkOnMainThreadException
任何帮助,将不胜感激。
Android 可能会很好地执行您的请求。您似乎只是忽略了服务器返回的数据。你可以这样做,例如:
public void changText(View view) {
TextView textv = (TextView)findViewById(R.id.textview1);
textv.setText("Text Has Been Changed");
BufferedReader in = null;
String data = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website = new URI("http://alanhardin.comyr.com/matt24/matt28.php");
request.setURI(website);
HttpResponse response = httpclient.execute(request);
in = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
// NEW CODE
String line = in.readLine();
textv.append(" First line: " + line);
// END OF NEW CODE
textv.append(" Connected ");
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
看起来您的服务器正在返回一个 JSON 对象,因此您可能想要做一些更智能的事情,例如读取整个响应,解析它(使用new JSONArray(response)
),并提取相关字段,但上面的代码至少会验证 Android 是否正在执行您的查询。
编辑:从您报告的异常来看,您似乎正在主 UI 线程上运行代码。从 API 11 开始,这是被禁止的(并且在此之前曾被人皱眉)。有几篇文章介绍了如何解决此问题。请参阅指南主题无痛穿线 http://android-developers.blogspot.com/2009/05/painless-threading.html以及教程here http://blog.vogella.com/2012/02/22/android-strictmode-networkonmainthreadexception/ and here http://www.techblogistech.com/2011/11/how-to-fix-the-android-networkonmainthreadexception/。另请参阅这个线程 https://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception了解更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)