当互联网连接时连接或读取超时时,Android显示Web服务中的超时消息

时间:2016-04-19 06:56:04

标签: android web-services connection-timeout

  

您好我需要显示消息"数据未收到"连接或读取超时。

     

我使用java.net.SocketTimeoutException实现此功能,但如果在连接互联网时没有收到数据,则无法收到消息。

     

我只通过互联网获得帮助。

     

但实际上我想在连接互联网时得到它。

互联网连接测试代码

public static boolean isNetworkConnected(Activity activity) {
    ConnectivityManager connectivity = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }

    }
    return false;
}

代码

@Override
protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    String result = "";
    try {
        URL url = new URL(params[0]);
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setRequestProperty("Accept", "application/json");
        httpConnection.setReadTimeout(10000);
        httpConnection.setConnectTimeout(15000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);

        OutputStream os = httpConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(String.valueOf(values));
        writer.flush();
        writer.close();
        os.close();

        int responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream iStream = httpConnection.getInputStream();
            InputStreamReader isReader = new InputStreamReader(iStream);
            BufferedReader br = new BufferedReader(isReader);
            String line;
            while ((line = br.readLine()) != null) {
                result += line;
            }
        }
    } catch (java.net.SocketTimeoutException e) {
        Toast.makeText(context, "Network Error : No Data Received.", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
        Log.e("Error : ", e.toString());
    }
    return result;
}

1 个答案:

答案 0 :(得分:0)

用于显示Toast:

catch (java.net.SocketTimeoutException e) {

    runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "Network Error : No Data Received.", Toast.LENGTH_SHORT).show();
                }
            });

}
catch (Exception e) {
    runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context,e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
}