HttpURLConnection非常慢

问题描述 投票:1回答:1

谁能发现为什么这需要~20秒?我正在运行下面的代码将JSON请求发布到本地服务器192.168.1.127。

curl -H“Content-type:application / json”-X POST http:// 192.168.1.127:8080/bed -d'{“command”:{“value”:3.012,“set”:“target_pressure_voltage”}, “ID”:2002年, “方”: “左”, “角色”: “命令”}”

卷曲在服务器运行的同一个盒子上是即时的,服务器不会抱怨。

来自Android浏览器的get请求很快。我已经尝试了两个运行os版本4.x的Android设备。

就我所知,这个问题无济于事:Android HttpURLConnection VERY slow

con.getInputStream()需要大约20秒:

    String httpJson(String url, JSONObject job) {
    String ret = null;      
        HttpURLConnection con = httpJsonCon(url);
        if(con!=null)
            httpJsonCon(con, url,job);      
    return ret;

}



 HttpURLConnection mkCon(String url) {
    HttpURLConnection con = null;
    URL u = null;
    try {
        u = new URL(url);
        con = (HttpURLConnection) (u.openConnection());

        con.setRequestMethod("POST");
        con.setUseCaches(false);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "text/plain");
        con.setRequestProperty("Accept", "application/json");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.connect();

    } catch (Exception e) {
        Log.w(TAG, " e= " + e);
        if(con!=null)
            con.disconnect();

        con = null;
    }

    return con;
}

String sendJson(HttpURLConnection con, JSONObject job) {
    String ret = null;
    if(con==null){
        return ret;
    }

    try {
        final String toWriteOut = job.toString();

        final Writer out = new OutputStreamWriter(new BufferedOutputStream(
                con.getOutputStream()), "UTF-8");
        out.write(toWriteOut);
        out.flush();
        //con.getInputStream() Takes ~20 sec:
        final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));  



    } catch (IOException e) {

        Log.d(TAG, " e= " + e);

        ret = null;
    } finally {
        if(con!=null)
            con.disconnect();
    }

    return ret;

}
java android
1个回答
0
投票

添加指定帖子内容长度的请求标头。

con.setRequestProperty("Content-Length", "" + json.length());
© www.soinside.com 2019 - 2024. All rights reserved.