gpt4 book ai didi

java - Android中如何使用HttpURLConnection来发布数据?

转载 作者:行者123 更新时间:2023-12-01 17:24:39 25 4
gpt4 key购买 nike

我想通过流将 json 数据发送到服务器,但我很难让它工作。我有以下方法:

String data = "{\"id\":\"2633\",\"f_name\":\"Test\",\"l_name\":\"Aplikace\",\"city\":\"Nymburk\",\"address\":\"Testovaci 123456789 xyz\",\"psc\":\"288 02\"}";


private String httpPost(String urlString, String data, String session_per) {
StringBuffer sb = new StringBuffer("");
String s1 = "";
try {
URL url = new URL(urlString);
String s2 = "";
HttpURLConnection httpurlconnection = (HttpURLConnection)url.openConnection();
httpurlconnection.setDoInput(true);
httpurlconnection.setDoOutput(true);
httpurlconnection.setUseCaches(false);
httpurlconnection.setRequestMethod("POST");
httpurlconnection.setRequestProperty("Cookie",session_per);
httpurlconnection.setRequestProperty("Authentication-Token", GlobalVar.KLIC);
httpurlconnection.setRequestProperty("Content-type", "application/json");
httpurlconnection.setAllowUserInteraction(false);

OutputStreamWriter outStrWrt = new OutputStreamWriter(httpurlconnection.getOutputStream());
outStrWrt.write(data);
outStrWrt.close();

String s3 = httpurlconnection.getResponseMessage();
//dataoutputstream.flush();
//dataoutputstream.close();
InputStream inputstream = httpurlconnection.getInputStream();
String line = "";
BufferedReader br = new BufferedReader(new InputStreamReader(inputstream));
int i;
while( (line = br.readLine()) != null) {
sb.append(line);
}
s1 = sb.toString();
}
catch(Exception ex)
{
ex.printStackTrace();
s1 = "";
}
return s1;
}

谁能告诉我为什么这不起作用? cookies等都是正确的。我错过了什么重要的事情吗?这就像我正在尝试的第六种方法,我开始变得绝望:D谢谢!

编辑:

连接成功,服务器有响应,但没有更新用户数据,就像 json 没有正确到达服务器一样。

如果我的 Java 代码正确,则可能存在服务器端问题。

最佳答案

尝试使用flush()方法,在读取所有字节之前不要关闭此输出流

outStrWrt.flush();
InputStream inputstream=httpurlconnection.getInputStream();

关于java - Android中如何使用HttpURLConnection来发布数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61226424/

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