2

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

curl -H "内容类型:应用程序/json" -X POST http://192.168.1.127:8080/bed -d '{"command":{"value":3.012,"set":"target_pressure_voltage"}, "id":2002,"side":"left","role":"command"}'

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

来自 Android 浏览器的获取请求很快。我尝试了两台操作系统版本为 4.x 的 Android 设备。

据我所知,这个问题没有帮助: Android HttpURLConnection 非常慢

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;

}
4

1 回答 1

0

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

con.setRequestProperty("Content-Length", "" + json.length());
于 2013-02-06T04:59:49.267 回答