gpt4 book ai didi

java - HttpURLConnection 很慢

转载 作者:行者123 更新时间:2023-11-29 09:06:30 35 4
gpt4 key购买 nike

谁能看出为什么这需要大约 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,"side":"left","role":"command"}'

在服务器运行的同一个盒子上 curl 是即时的,服务器不会提示。

来自 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;

}

最佳答案

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

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

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

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com