httpURLConnection使我的应用程序停止

时间:2017-07-24 15:12:41

标签: android connection httpurlconnection

大家好,希望你做得好 我的应用程序有问题,我使用下面的代码连接到某个地址(正如你在这里看到它的本地地址)我的问题是当我关闭我的wamp服务器或者例如我的应用程序无法连接到地址我以前给过它,我的应用程序在特殊时间后停止,它给了我一个错误。 我想知道如何将代码更改为应用程序无法找到地址(出于任何原因),我的应用程序向用户发出消息而不是保留stops.how我可以处理吗?

这是我的代码

String json_url = "http://10.0.2.2/ss/1.php";
    @Override
    protected String doInBackground(Void...voids){
        try{
            URL url = new URL(json_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            while((json_string=bufferedReader.readLine())!=null){
                stringBuilder.append(json_string+"\n");
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return stringBuilder.toString().trim();
        } catch (MalformedURLException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
            System.out.println("Deal With Wrong Address");
            return null;
        }
        return null;
    }

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

首先您应该检查您的应用程序是否具有Internet连接,然后只调用此方法。

 ConnectivityManager connMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
// Do stuff here for API call
}

一旦调用,您可以进一步捕获超时异常并在try catch

中显示自定义消息

添加以下catch块

        }catch (SocketTimeoutException bug) {
            Toast.makeText(getApplicationContext(), "Socket Timeout", Toast.LENGTH_LONG).show();
        } catch (ConnectTimeoutException bug) {
            Toast.makeText(getApplicationContext(), "Connection Timeout", Toast.LENGTH_LONG).show();
        }

还可以使用 -

为您的请求设置connectionTimeout参数
httpURLConnection.setConnectTimeout(5000); // 5 sec timeout

答案 1 :(得分:0)

伙计们,我想我已经解决了这个问题 我只需要这一行

return String.valueOf(0);

而不是

return null;

但很多感谢kapsym