gpt4 book ai didi

Android HTTP 获取

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:43:21 25 4
gpt4 key购买 nike

我查看了一些论坛帖子,但找不到我的问题的答案。我正在尝试从 php 文件中获取响应。 php 文件正在运行。问题是 Android 应用程序不会执行我的请求。以下是我的代码的两个示例以及我在 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 显示:Text Has Been Changed

    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 显示:Text Has Been Changed Connected

在这份 list 中我有:

<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 开始,这是被禁止的(并且在此之前是不受欢迎的)。有几篇文章介绍如何解决此问题。请参阅指南主题 Painless threading以及教程herehere .另见 this thread获取更多信息。

关于Android HTTP 获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20321799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com