在Android 5.1,android6.0上的httpurlconnection SocketTimeoutException

时间:2016-12-27 04:04:19

标签: android sockets timeout httpurlconnection

我使用HttpUrlConnection发送一个帖子请求,但是在与Android 5.1(包括android 5.1)上面的服务器通信时我得到java.net.SocketTimeoutException异常,但在android 5.1下面的帖子请求是正常的。这是我的代码:< / p>

String postMethod() throws IOException {

    String json = JsonParser.toJson(req);
    Log.d("dzq", "request:" + json);
    if (TextUtils.isEmpty(json)) return null;
    byte[] data = json.getBytes();

    GZIPInputStream gzipInputStream;
    ByteArrayOutputStream baos;
    InputStream inStrm;
    HttpURLConnection conn;

    conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setReadTimeout(60*1000);
    conn.setConnectTimeout(60*1000);
    conn.setRequestMethod("POST");
        /* 允许Input、Output,不使用Cache */
    conn.setDoInput(true); // 表示从服务器获取数据
    conn.setDoOutput(true);// 表示向服务器写数据
    conn.setUseCaches(true); //不使用缓存,每次请求的数据,都需要是新的
    conn.setRequestProperty("Content-Type", "application/x-tar");
    conn.setRequestProperty("Content-Length", String.valueOf(data.length));
    conn.setRequestProperty("Accept-Encoding", "gzip");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Charset", "UTF-8");

    BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream());
    bos.write(json.getBytes());
    bos.flush();
    bos.close();

    int status;
    inStrm = conn.getInputStream(); // <===注意,实际发送请求的代码段就在这里
    status = conn.getResponseCode();

    if (status == HttpURLConnection.HTTP_OK) {
        String contentEncoding = conn.getContentEncoding();
        /** 判断是否是GZIP **/
        boolean isGzipEncoding = false;

        // 读取数据
        if ((null != contentEncoding)
                && contentEncoding.equalsIgnoreCase("gzip")) {
            isGzipEncoding = true;
        }

        if (isGzipEncoding) {
            // 如果是GZIP压缩
            gzipInputStream = new GZIPInputStream(inStrm);
            baos = new ByteArrayOutputStream();
            byte[] readBuffer = new byte[1024];
            int len;
            while ((len = gzipInputStream.read(readBuffer)) != -1) {
                baos.write(readBuffer, 0, len);
            }

            return baos.toString("utf-8");

        } else {
            baos = new ByteArrayOutputStream();
            int len;
            byte[] readBuffer = new byte[1024];
            while ((len = inStrm.read(readBuffer)) != -1) {
                baos.write(readBuffer, 0, len);
            }

            return baos.toString("utf-8");
        }
    }

    conn.disconnect();

    try {
        if (null != inStrm) {
            inStrm.close();
        }

    } catch (Exception ignored) {
    }
    return null;
}

JSON:

{
  "userAgent": {
    "imsi": "460013882300329",
    "imei": "867694020669042",
    "androidSystemVer": "5.1.1",
    "screenSize": "1440*2560",
    "ramSize": "3712",
    "romSize": "56056",
    "cpu": "AArch64 Processor rev 2 (aarch64) ",
    "hsman": "Xiaomi",
    "hstype": "MI NOTE Pro",
    "networkType": "3",
    "provider": "中国联通",
    "packageName": "com.jolo.push4_0",
    "apkVer": "1.0001",
    "dpi": "640",
    "apkVerInt": "100001",
    "mac": "58:44:98:43:fe:cd",
    "installTime": "1482807931757",
    "terminalId": "",
    "channelCode": "74999699",
    "lat": "0.0",
    "lng": "0.0"
  },
  "businessCode": 2001,
  "uuid": "",
  "userApks": "H4sIAAAAAAAAAFVW23KjOhD8FT+eU+WdkrhTftqn87TfkBKggGKQCAI7+OtPj4SdbKUSOdagmenpbtG6iYa5Wahx3j8GMxt7OueUitO5Si4tdkfnrvxLX8b2g7P9uzavL09nSQiVF7f01Ot1VHbVi6VjPZ1TSig//ZMIWUiRZCSrpEjkv6dzkhQiy2VShyTWKNfrxnwY7JAgiTPLsDO5fvsw+nSuSeInzUrkq6UUQoR9ZbvFmY4aZa+qaTljHkpKw/aHG6zdqccu14pzY1fejNq2uttWulp3v2u1DnoJIaj3LLNLa4kD3awtinAtwyIowyKymNq8j/uqr+RnrduhHd3WBTwIxeUpPvISIjujLJDt6SZjI6EHIeMxD+U65aifPT+ehvz5pZ0ampuYVXLWGP2+WT8YZ+lmOu1oHtXOdQs8J3FqEktrlOk2Mnbe1rfJ3IrTuQAsOeBHiBSXSZMeAWpJCZIlEeqVEbErTROHp5Riry7igR7H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kGt2Rc+PnoeVl+qEG5yUQcnw6E7JLtWeBN42fQgFcejb4HZmASrs30OdknkcJtPm3etK/2quKy3rhMCGEjKN0EokWNpGx1FzxNzrcD9xnuhxs4TPKfQEPIOE/4zefwYP19o/wezaz2/2YolUcgwrWBRxLB7wJH9fM8mtuLwDAjDPlvLzGbeb0WbD0zmmkEzqVPZb4y4uaInMWsq+zyP0nx3c4HCgAA"
}

logcat的:

com.jolo.push4_0.net.response.GetAdSdkConfigResp@274e153fjava.net.SocketTimeoutException
12-27 11:06:06.121 10462-11341/com.jolo.push4_0 W/System.err:     at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
12-27 11:06:06.121 10462-11341/com.jolo.push4_0 W/System.err:     at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:37)
12-27 11:06:06.121 10462-11341/com.jolo.push4_0 W/System.err:     at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:237)
12-27 11:06:06.121 10462-11341/com.jolo.push4_0 W/System.err:     at com.android.okio.Okio$2.read(Okio.java:113)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at com.android.okio.RealBufferedSource.indexOf(RealBufferedSource.java:147)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at com.android.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:94)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:179)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:101)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:628)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:388)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:199)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at com.jolo.push4_0.net.OkHttpWrapper.postMethod(OkHttpWrapper.java:76)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at com.jolo.push4_0.net.BaseNetUtil$NetTask.doInBackground(BaseNetUtil.java:72)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at com.jolo.push4_0.net.BaseNetUtil$NetTask.doInBackground(BaseNetUtil.java:64)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:292)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-27 11:06:06.131 10462-11341/com.jolo.push4_0 W/System.err:     at java.lang.Thread.run(Thread.java:818)

如果你能给我一些建议,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

来自https://stackoverflow.com/a/24614909/7267105

客户端无法解决错误,因为它是与网络相关的问题。但是,您可以做的是重试连接几次。这可以作为一种解决方法,直到真正的问题得到解决。

scanf("%s",book_name);
printf("Please enter author name:\n");
scanf("%s",author_name);
printf("Please enter publisher name:\n");
scanf("%s",publisher_name);
printf("Please enter book genre:\n");
scanf("%s",book_genre);