我看了一些论坛帖子,我无法找到问题的答案.我想从一个php文件得到一个响应.php文件正常运行.问题是Android App不会执行我的请求.以下是我的代码的两个示例以及我在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显示:文本已更改
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显示:文本已更改已连接
在这个清单中我有:
在错误日志中,我得到以下内容: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被禁止(并且在此之前不赞成).有几篇关于如何解决这个问题的文章.请参阅指南主题无痛线程以及此处和此处的教程.另请参阅此主题以获取更多信息.