Android getOutputStream()连接超时错误

时间:2017-01-16 16:08:22

标签: android timeout httpurlconnection

我有两个HttpURLConnection方法,一个GET,另一个POST,使用GET一个我对超时没有任何问题,但是对于POST我发现方法getOutputStream()不尊重超时,什么我做错了?

public String doPost(String url, String nif, String credencial) {
    HttpURLConnection urlConnection = null;
    try {
        URL requestedUrl = new URL(url);
        urlConnection = (HttpURLConnection) requestedUrl.openConnection();
        if(urlConnection instanceof HttpsURLConnection) {
            ((HttpsURLConnection)urlConnection).setSSLSocketFactory(sslContext.getSocketFactory());
        }
        urlConnection.setRequestMethod("POST");
        urlConnection.setConnectTimeout(1500);
        urlConnection.setReadTimeout(1500);
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        JSONObject mijs = new JSONObject();

        mijs.put("TEST", test);
        mijs.put("TEST2", test2);

        OutputStreamWriter wr= new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(mijs.toString());

        wr.flush();
        wr.close();

        int status = urlConnection.getResponseCode();

        lastResponseCode = urlConnection.getResponseCode();

        if (status != HttpURLConnection.HTTP_OK) {
            result = IOUtil.readFully(urlConnection.getErrorStream());
        } else {
            result = IOUtil.readFully(urlConnection.getInputStream());
        }
    } catch (SocketTimeoutException e) {
        result = "0";
    } catch(Exception ex) {
        result = "0";
    } finally {
        if(urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    return result;
}

谢谢!

0 个答案:

没有答案