【发布时间】:2020-01-14 03:19:22
【问题描述】:
NOTICE UPDATE!!
The problem got solved and i added my own answer in the thread
简而言之,我尝试添加参数“scan_id”值,但由于它是一个 POST,我无法直接在 url 路径中添加该值。
使用我已经拥有的代码,我将如何修改或添加以使 url 正确,也就是说,以便它接受我的 POST?。
不知何故,我找不到任何可以帮助我弄清楚我将如何去做的例子。
我知道如何使用有效负载进行 POST,使用参数进行 GET。但是 Params 的帖子让我很困惑。
感谢任何帮助。 (我想继续使用 HttpUrlConnection ,除非提供了另一个示例,该示例还告诉我如何发送请求而不仅仅是配置路径。
我已经尝试将它添加到有效负载中。 我已经尝试过 UriBuilder,但发现它令人困惑并且与我的其余代码形成对比,因此想寻求有关 HttpUrlConnection 的帮助。
URL url = new URL("http://localhost/scans/{scan_id}/launch");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("tmp_value_dont_mind_this", "432432");
con.setRequestProperty("X-Cookie", "token=" + "43432");
con.setRequestProperty("X-ApiKeys", "accessKey="+"43234;" + " secretKey="+"43234;");
con.setDoInput(true);
con.setDoOutput(true); //NOT NEEDED FOR GETS
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
//First example of writing (works when writing a payload)
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
//second attemp at writing, doens't work (wanted to replace {scan_id} in the url)
DataOutputStream writer = new DataOutputStream(con.getOutputStream());
writer.writeChars("scan_id=42324"); //tried writing directly
//writer.write(payload);
writer.close();
例外:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost/scans/launch
我想要三个响应代码之一,因为这样我就知道 URL 是正确的:
200 Returned if the scan was successfully launched.
403 Returned if the scan is disabled.
404 Returned if the scan does not exist.
我已经尝试了几个网址
localhost/scans/launch,
localhost/scans//launch,
localhost/scans/?/launch,
localhost/scans/{scan_id}/launch,
【问题讨论】:
-
你使用的是路径参数吗?
scan_id=42324是一个查询参数。在您的情况下,路径参数应为http://localhost/scans/42324/launch。 -
我相信我希望 42324 出现在查询中。当我发送路径localhost/scans/42324/launch 时,API 不理解它并以 400 响应代码响应。
标签: java rest post parameters httpurlconnection