【问题标题】:How to get remote url content using HttpURLConnection in android?如何在 android 中使用 HttpURLConnection 获取远程 url 内容?
【发布时间】:2017-11-20 02:40:03
【问题描述】:

我正在尝试使用 HttpURLConnection 获取远程 url 内容,但我一直得到空结果。通过查看 charle 代理,我可以看到 get 请求已执行,但 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";

            }


        }

    }

【问题讨论】:

  • setDoOutput 是用于 POST 请求的,而且您在打开连接之前也得到了它,也不知道预期的结果,为什么 URL 是 javascript?

标签: android httpurlconnection


【解决方案1】:

你应该检查异常:

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

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

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

请参阅此文档:

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

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

如果您在 Activity 中创建了 AsyncTask ,则可以使用它,否则您应该创建一个 Interface 类并传入 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+ "')");
}

}

【讨论】:

  • 感谢您的回复。但是如何将响应从受保护的 String doInBackground(String... urls) { 转移到 webview 而不跳帧?我试图在 doInBackground(String... urls) { 中发出 get 请求,但不知道如何将响应发送到 webView UI!
  • 使用 onPostExecute 方法刷新你的 UI
  • 我更新了我的第一篇文章。你能看看它并告诉我如何使用 onPostExecute 将结果传递给 webview javascript 函数吗?
  • 我想从我网站的 url 中获取一个 m3u 列表,但我不断收到以下错误。有什么解决办法吗?error I/Choreographer: Skipped 10132 frames!应用程序可能在其主线程上做了太多工作。 I/Choreographer:跳过了 690 帧!应用程序可能在其主线程上做了太多工作。
  • 这个解决方案对您有用吗?错误是什么?给我们更多的细节,“应用程序可能在它的主线程上做太多的工作”这个消息是因为你在主线程中做长时间的操作
猜你喜欢
  • 2018-05-05
  • 2013-02-10
  • 1970-01-01
  • 2016-12-09
  • 2020-07-17
  • 2016-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多