有谁能发现为什么这需要大约20秒? 我正在运行下面的代码将JSON请求发布到本地服务器192.168.1.127。
curl -H“Content-type:application / json”-X POST http:// 192.168.1.127:8080/bed -d '{ “命令”:{ “值”:3.012, “设置”: “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;
}
答案 0 :(得分:0)
添加一个指定帖子内容长度的请求标头。
con.setRequestProperty("Content-Length", "" + json.length());