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


  curl -H“内容类型:application / 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 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;

}

最佳答案

添加一个指定标头内容长度的请求标头。

con.setRequestProperty("Content-Length", "" + json.length());

关于java - HttpURLConnection很慢,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14717752/

10-12 05:54