Http Post - 通信失败 - 为什么?



我用Java(Android Studio(编写了一个HTTP POST,以便从NodeRed数据库中获取一些信息。

当我执行此代码时,不会发生任何错误。但是数据库会创建一个包含空字段的条目,并且应该给出包含数据的 JsonArray 的响应只是一个空的 JsonArray。

有人看到错误吗?如果我用邮递员测试数据库,一切正常。不仅如此,我已经编写了一个没有任何参数的 GET,它也可以正常工作。

这是我的 POST 方法:

URL url = new URL("https://example-page.de/ExistingUser");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
String boundary = "===" + System.currentTimeMillis() + "===";
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); 
con.setRequestProperty("Accept", "*/*");
con.setRequestProperty("Host", "example-page.de");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Cache-control", "no-cache");
con.setUseCaches (false);
con.setDoInput(true);
con.setDoOutput(true);
//Create REQUEST content
DataOutputStream wr = new DataOutputStream(con.getOutputStream ());
PrintWriter writer;
String LINE_FEED = "rn";
String charset = "UTF-8";
String name = "EMail";
String value = "hans.wurst";
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name="" + name + """).append(LINE_FEED);
writer.append("Content-Type: application/json; charset=" + charset).append(LINE_FEED);
writer.append(LINE_FEED);
writer.append(value);
writer.flush();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
//Read Response
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();

我只在正文中输入此参数。

您似乎尚未将表单数据部分添加到正确的输出流中。 您无需创建其他版画。

DataOutputStream wr = new DataOutputStream(con.getOutputStream ());
//PrintWriter writer;
String LINE_FEED = "rn";
String charset = "UTF-8";
String name = "EMail";
String value = "hans.wurst";
wr.append("--" + boundary).append(LINE_FEED);
wr.append("Content-Disposition: form-data; name="" + name + """).append(LINE_FEED);
wr.append("Content-Type: application/json; charset=" + charset).append(LINE_FEED);
wr.append(LINE_FEED);
wr.append(value);
wr.flush();
wr.append(LINE_FEED).flush();
wr.append("--" + boundary + "--").append(LINE_FEED);
wr.close();

首先感谢您的帮助!

我试过了,但没有用。 我们大学的服务器上有一个虚拟机。我们的 URL 通过服务器内部的默认端口传递到我们的虚拟机。这可能是问题所在吗?因此,也许正文的内容没有从第一个网络服务器传递到我们的第二个网络服务器?因为如果我使用查询参数或在标头内创建新的键值对,则没有问题。一切正常。

但现在我有另一个问题。当我使用查询参数执行 GET 请求时,我可以使用普通 URL。但是当我尝试使用查询参数进行 POST 时,我需要使用服务器的本地 IP 并将我的手机连接到我大学的本地网络。这很令人困惑,我看不出有什么原因吗? 你有想法吗?

最新更新