Android 安卓 HTTP 获取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20321799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:38:32  来源:igfitidea点击:

Android HTTP Get

androidhttpclienthttp-get

提问by user908759

I've look at a few forum post and I can not find an answer to my problem. I am trying to get a response from a php file. The php file is working. The problem is the Android App will not execute my request. Here are two examples of my code and the result I get in the textview:

我查看了一些论坛帖子,但找不到问题的答案。我正在尝试从 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());
       }


   }

The TextView reads: Text Has Been Changed

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());
       }


   }

The TextView reads: Text Has Been Changed Connected

TextView 上写着:Text Has been Changed Connected

In this manifest I have:

在这个清单中,我有:

<uses-permission android:name="android.permission.INTERNET" />

In the error log I get the following: Error in http connection android.os.NetworkOnMainThreadException

在错误日志中,我得到以下信息:http 连接错误 android.os.NetworkOnMainThreadException

Any help would be appreciated.

任何帮助,将不胜感激。

回答by Ted Hopp

Android is probably executing your request just fine. You just seem to be ignoring the data returned by the server. You could do something like this, for instance:

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());
       }
}

It looks like your server is returning a JSON object, so you would probably want to do something more intelligent such as read the entire response, parse it (using new JSONArray(response)), and extract relevant fields, but the above code would at least verify that Android is executing your query.

看起来您的服务器正在返回一个 JSON 对象,因此您可能想要做一些更智能的事情,例如读取整个响应、解析它(使用new JSONArray(response))并提取相关字段,但上面的代码至少可以验证 Android 是执行您的查询。

EDIT: From the exception you report, it appears that you are running your code on the main UI thread. As of API 11 that is prohibited (and was frowned upon before that). There are several articles on how to fix this. See the Guide topic Painless threadingas well as tutorials hereand here. Also see this threadfor more information.

编辑:从您报告的异常来看,您似乎是在主 UI 线程上运行代码。从 API 11 开始,这是被禁止的(并且在此之前不受欢迎)。有几篇文章介绍了如何解决此问题。请参阅指南主题无痛线程以及此处此处的教程。另请参阅此线程以获取更多信息。

回答by Raj008

 private InputStream downloadUrl(final URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(NET_READ_TIMEOUT_MILLIS /* milliseconds */);
    conn.setConnectTimeout(NET_CONNECT_TIMEOUT_MILLIS /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    return conn.getInputStream();
}