如何在android中使用HttpURLConnection获取远程url内容?

时间:2017-11-20 02:40:03

标签: android httpurlconnection

我正在尝试使用HttpURLConnection获取远程url内容,但我一直得到空的结果。通过查看charle代理我可以看到执行获取请求但android无法保存响应!你能告诉我的是什么这段代码有问题吗?先谢谢。

public String sendGetRequest() {


        try {

            StrictMode.setThreadPolicy(new Builder().permitAll().build());

            HttpURLConnection myURLConnection = (HttpURLConnection) new URL("http://www.bbc.com").openConnection();
            myURLConnection.setReadTimeout(60000);
            myURLConnection.setConnectTimeout(60000);
            myURLConnection.setRequestMethod("GET");
            myURLConnection.setUseCaches(false);
            myURLConnection.setDoInput(true);
            myURLConnection.setDoOutput(true);
            myURLConnection.setRequestProperty("Content-Type", "text/plain");
            myURLConnection.setRequestProperty("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 6.0;)");

            myURLConnection.setRequestProperty("Connection", "Keep-Alive");
            myURLConnection.addRequestProperty("Content-length", "");

            OutputStream os = myURLConnection.getOutputStream();

            os.close();

            myURLConnection.connect();

            BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));

            StringBuffer sb = new StringBuffer();

            String line;


            while ((line = in.readLine()) != null) {

                sb.append(line);

            }


            in.close();

            return sb.toString();

        } catch (Exception e) {

        }
        return null;

    }

然后我点击按钮调用上述功能:

public Button but1;

//creating public method
public void init() {

but1 = (Button) findViewById(R.id.but1);


//wire our button
but1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {



        String finalResult = sendGetRequest();
        mWebView.loadUrl("javascript:displayIt(" + finalResult+ ")");
    }
});

}

编辑(使用后台进程):

 public class DownloadTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {

            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;

            try {

                url = new URL(urls[0]);

                urlConnection = (HttpURLConnection) url.openConnection();

                InputStream in = urlConnection.getInputStream();

                InputStreamReader reader = new InputStreamReader(in);

                int data = reader.read();

                while (data != -1) {

                    char current = (char) data;

                    result += current;

                    data = reader.read();

                }

                return result;

            } catch (Exception e) {

                e.printStackTrace();

                return "Failed";

            }


        }

    }

1 个答案:

答案 0 :(得分:1)

你应该检查例外:

catch (Exception e) {
    e.printStackTrace();
        }

我确定这是因为你在主线程上进行了长时间的操作。

你必须在后台线程中进行长时间的操作。

请参阅此文档:

https://developer.android.com/reference/android/os/AsyncTask.html https://developer.android.com/training/multiple-threads/communicate-ui.html

使用您更新的问题进行更新

如果你在Activity中创建了AsyncTask,你可以使用其他你应该在AsyncTask的构造函数中创建一个接口类传递

but1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
         new DownloadTask().execute("http://www.bbc.com");
    }
});

     public class DownloadTask extends AsyncTask<String, Void, String> {



 @Override
    protected String doInBackground(String... urls) {

    String result = "";
    URL url;
    HttpURLConnection urlConnection = null;

    try {

        url = new URL(urls[0]);

        urlConnection = (HttpURLConnection) url.openConnection();

        InputStream in = urlConnection.getInputStream();

        InputStreamReader reader = new InputStreamReader(in);

        int data = reader.read();

        while (data != -1) {

            char current = (char) data;

            result += current;

            data = reader.read();

        }

        return result;

    } catch (Exception e) {

        e.printStackTrace();

        return "Failed";

    }


}


@Override
protected void onPostExecute(String result){
    mWebView.loadUrl("javascript:displayIt('" + result+ "')");
}

}