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

如何在android中使用HttpURLConnection获取远程url内容?,android,httpurlconnection,Android,Httpurlconnection,我正在尝试使用HttpURLConnection获取远程url内容,但结果一直为空。通过查看charle proxy,我可以看到执行了get请求,但android无法保存响应!你们能告诉我这个代码有什么问题吗?提前谢谢 public String sendGetRequest() { try { StrictMode.setThreadPolicy(new Builder().permitAll().build()); Ht

我正在尝试使用HttpURLConnection获取远程url内容,但结果一直为空。通过查看charle proxy,我可以看到执行了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+ ")");
    }
});
}

编辑(用于后台处理):

公共类下载任务扩展了异步任务{
@凌驾
受保护的字符串doInBackground(字符串…URL){
字符串结果=”;
网址;
HttpURLConnection-urlConnection=null;
试一试{
url=新url(url[0]);
urlConnection=(HttpURLConnection)url.openConnection();
InputStream in=urlConnection.getInputStream();
InputStreamReader reader=新的InputStreamReader(in);
int data=reader.read();
while(数据!=-1){
当前字符=(字符)数据;
结果+=电流;
data=reader.read();
}
返回结果;
}捕获(例外e){
e、 printStackTrace();
返回“失败”;
}
}
}

您应该检查异常:

catch (Exception e) {
    e.printStackTrace();
        }
我确信这是因为你在主线程上做了长时间的操作

您必须在后台线程中执行长操作

请参阅本文档:

使用更新的问题进行更新

如果您在活动中创建了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+ "')");
}

}
but1.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
新建下载任务()。执行(“http://www.bbc.com");
}
});
公共类DownloadTask扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(字符串…URL){
字符串结果=”;
网址;
HttpURLConnection-urlConnection=null;
试一试{
url=新url(url[0]);
urlConnection=(HttpURLConnection)url.openConnection();
InputStream in=urlConnection.getInputStream();
InputStreamReader reader=新的InputStreamReader(in);
int data=reader.read();
while(数据!=-1){
当前字符=(字符)数据;
结果+=电流;
data=reader.read();
}
返回结果;
}捕获(例外e){
e、 printStackTrace();
返回“失败”;
}
}
@凌驾
受保护的void onPostExecute(字符串结果){
loadUrl(“javascript:displayIt(““+result+”)”);
}
}

谢谢您的回复。但是如何将响应从受保护的字符串doInBackground(String…url){传输到webview而不跳过帧呢?我尝试在doInBackground(String…url)内部发出get请求{但不知道如何将响应发送到webView UI!使用onPostExecute方法刷新您的UII更新了我的第一篇文章。您能看看它并告诉我如何使用onPostExecute将结果传递到webView javascript函数吗?我想从我网站中的url获取一个m3u列表,并且不断出现以下错误。是否有任何解决方案可以解决此问题或者它?错误I/Choreographer:跳过了10132帧!应用程序可能在其主线程上做了太多工作。I/Choreographer:跳过了690帧!应用程序可能在其主线程上做了太多工作。此解决方案对您有效吗?错误是什么?请提供更多详细信息,“应用程序可能在其主线程上做了太多工作”此消息是因为您正在主线程中执行长操作SetDoOutput用于POST请求,并且您在打开连接之前也得到了它,不知道预期结果,还有,为什么URL是javascript?
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+ "')");
}

}