Android Java-HttpURLConnection失败而未引发异常

时间:2018-10-09 16:46:56

标签: java android http exception inputstream

我正在AsyncTask内运行HTTPUrlConnection以便从API检索JSON数据,但是它似乎失败了并且崩溃了我的应用程序,而没有碰到catch / finally代码。值得注意的是,URL是https,如果我将其更改为http,则会收到关于不允许进行明文通信的错误消息(如果我为此连接使用任何URL,即使是https://www.google.com vs http://www.google.com,所以也许有些事情。

无论如何,我对如何进行一无所知。如果我在每行放置日志记录,则此操作将停止并在getResponseCode()行崩溃,如果我删除该日志,则此刻将停止并在getInputStream()行崩溃。如果我删除超时,也​​没有区别。任何帮助将不胜感激。

public static String getResponseFromHttpUrl(URL url) throws IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setConnectTimeout(500);
        urlConnection.setReadTimeout(500);

        int statusCode = urlConnection.getResponseCode();

        InputStream in = urlConnection.getInputStream();

        Scanner scanner = new Scanner(in);

        scanner.useDelimiter("\\A");

        boolean hasInput = scanner.hasNext();

        if (hasInput) {
            return scanner.next();
        } else {
            return null;
        }
    }
    catch(Exception ex){
        Log.d("NetworkUtils", "error in HTTP request");
        return null;
    }
    finally {
        Log.d("NetworkUtils", "before disconnect");
        if(urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这是功能AsyncTask,它不会抛出NetworkOnMainThreadException

public class UrlConnectionTask extends AsyncTask<Bundle, Integer, String> {

    private HttpURLConnection urlConnection = null;
    private URL url = null;

    public UrlConnectionTask(String spec) {
        try {
            this.url = new URL(spec);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(Bundle... bundles) {
        StringBuilder result = new StringBuilder();
        if(this.url != null) {
            try {

                this.urlConnection = (HttpURLConnection) url.openConnection();
                this.urlConnection.setConnectTimeout(5000);
                this.urlConnection.setReadTimeout(5000);

                if(this.urlConnection.getResponseCode() == 200) {
                    InputStream is = this.urlConnection.getInputStream();
                    BufferedReader r = new BufferedReader(new InputStreamReader(is));
                    String inputLine;
                    while ((inputLine = r.readLine()) != null) {
                        result.append(inputLine);
                    }
                    is.close();
                    t.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return result.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        System.out.println(result);
        if (this.urlConnection != null) {
            this.urlConnection.disconnect();
        }
    }
}

就这样,用new UrlConnectionTask("https://www.google.com").execute();调用-如果要返回HTML;您必须将侦听器传递到其构造函数中-然后在onPostExecute()上调用侦听器的方法之一。还可以检查所传递的url字符串是否有效,然后取消该任务,或者在HTTP响应不是200时调用错误侦听器。