Android: HttpUrlConnection 返回空输出

Android: HttpUrlConnection returning empty output

所以我正在尝试从 URL 读取流并将结果设置在文本视图中。 问题是代码 Android studio 没有在我的设备上返回任何结果,而 net beans 上的相同代码 returns 流输出。我不明白问题出在哪里,因为我使用的代码与 Android studio 和 Netbeans.Als android studio 上的应用程序没有崩溃或抛出任何错误。

只是想让你知道,我已经在 phone 的浏览器中打开了 android 工作室代码中的 URL,它正在运行。我还在清单中添加了互联网权限。我确实将函数 changeText 放在了 "onClick" 属性中。

以下代码已在 NetBeans 和 Android Studio(在我的 galaxy S6 上)上进行了测试。

Android工作室代码:

       package com.example.mohammed.acc;

    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.TextView;

    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;

    public class MainActivity extends AppCompatActivity {

        public void changeText (View v){
            TextView t1 = (TextView)findViewById(R.id.t1);
            URL url;
            HttpURLConnection con;

            try{
                StringBuilder sb = new StringBuilder();
                url = new URL("http://192.168.1.104:8000/api");
                con = (HttpURLConnection) url.openConnection();
                BufferedInputStream in = new BufferedInputStream(con.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String Line = "";

                while((Line = reader.readLine()) != null){
                    sb.append(Line);
                }

                t1.append(sb.toString());
                in.close();




}
        catch (MalformedURLException ex) {
           t1.setText(ex.getMessage());
        }
        catch (IOException ex){
            t1.setText(ex.getMessage());
        } catch (Exception ex){
            t1.setText(ex.getMessage());
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
}

NetBeans 代码:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication21;


import java.io.BufferedInputStream;
import java.util.Stack;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class JavaApplication21 {


    public static void main(String[] args) {
         try{
            StringBuilder sb = new StringBuilder();
            URL url = new URL("http://127.0.0.1:8000/api");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedInputStream in = new BufferedInputStream(con.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String Line = "";

            while((Line = reader.readLine()) != null){
                sb.append(Line);
            }
            System.out.print(sb.toString());
            in.close();
        }
        catch (Exception ex){
            System.out.print(ex.getMessage());
        }

    }

}

NetBeans 输出: 如您所见,它正在工作。 Android工作室,我的phone输出: 记录快照 这是在 运行 并单击按钮之后。

如果调用您的代码,它应该会导致 NetworkOnMainThreadException(您不能在主线程上进行网络调用)。因此很可能它根本没有被调用,并且您的按钮处理代码已损坏。

实际上,我看到您正在捕获异常。所以是的,它会抛出 NetworkOnMainThreadException,而您正在捕获并忽略它。如果您不厌其烦地将异常打印到日志中,即使是在调试器中进行基本单步执行或阅读日志也会告诉您。如果您不在某处打印异常,那么如果您没有看到任何错误但什么也没有发生,请不要感到惊讶。

也不是错误,但是 运行在事件处理程序中使用 findViewById 被认为是一种不好的做法。这些应该 运行 onCreate 一次,结果被缓存。

我看到 2 个问题:

1:你的http io不是在工作线程中执行的;

2:运行时未请求权限(您的api级别可能在22以上);

import android.annotation.TargetApi;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.root.myapplication.R;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {


    @TargetApi(23)
    protected void askPermissions() {
        String[] permissions = {
                "android.permission.INTERNET"
        };
        int requestCode = 200;
        requestPermissions(permissions, requestCode);
    }

    public void changeText (View v){

        final TextView t1 = (TextView)findViewById(R.id.t1);

        new AsyncTask<Void,Void,Void>(){
            private Exception exception;
            private StringBuilder sb;
            @Override
            protected Void doInBackground(Void... voids) {
                try{
                    sb = new StringBuilder();
                    URL url;
                    HttpURLConnection con;
                    url= new URL("http://peyvandha.ir");
                    con= (HttpURLConnection) url.openConnection();
                    BufferedInputStream in = new BufferedInputStream(con.getInputStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    String Line = "";
                    while((Line = reader.readLine()) != null){
                        sb.append(Line);
                    }
                    in.close();
                }catch (Exception ex){
                    this.exception=ex;
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                if(sb!=null){
                    //do what you do;
                    t1.setText(sb.toString());
                }else {
                    t1.setText(exception.getMessage());
                }
                super.onPostExecute(aVoid);
            }
        }.execute();

    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(Build.VERSION.SDK_INT>22)askPermissions();

    }
}