从Android应用接收套接字关闭的异常

时间:2019-07-14 11:15:06

标签: java android sockets http

我正在尝试连接服务器,有时我的Android应用程序出现“套接字关闭”异常(请参见下面的代码)。 这是我的代码:

try {
        url = new URL(isWebUrl ? "https://engaged.co.il/components/com_vreview/" + requestURL : "http://xn----8hchixdo5d.co.il/app/" + requestURL);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(50 * 1000);
        httpURLConnection.setReadTimeout(50 * 1000);
        new Thread(new InterruptThread(Thread.currentThread(), httpURLConnection)).start();
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        OutputStream outputStream = httpURLConnection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        bufferedWriter.write(getPostDataString(postDataParams));
        bufferedWriter.flush();
        int responseCode = httpURLConnection.getResponseCode();
        // If the connection is success.
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            // The data that will return is by jsonString.
            StringBuilder stringBuilder = new StringBuilder();
            String jsonString;
            while ((jsonString = bufferedReader.readLine()) != null) {
                stringBuilder.append(jsonString + "\n");
            }
            httpURLConnection.disconnect();
            bufferedWriter.close();
            outputStream.close();
            return stringBuilder.toString().trim();
        } else {
            // Connection failed
            response = "error";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

0 个答案:

没有答案