java - 在 Java REST 中为路径参数添加值?

标签 java rest post parameters httpurlconnection

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):

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,

最佳答案

所以在 friend 和这里的每个人的帮助下,我解决了我的问题。

下面的代码是对整个类中的所有代码的逐条解释。在底部你有完整的类及其所有语法等,它接受参数并返回一个字符串。

在 HTTP 请求中有特定的部分。 在我的案例中,这些部分包括请求 header 、Url 中的参数和有效负载。

根据 API,API 所需的某些变量需要进入其各自的类别。

My ORIGINAL URL looked like this: "http://host:port/scans/{scan_id}/export?{history_id}"
I CHANGED to: "https://host:port/scans/" + scan_Id + "/export?history_id=" + ID;

我正在调用的 API 需要在负载中有一个名为“format”的参数和一个值。

String payload = "{\"format\" : \"csv\"}";

因此,我使用我的新 URL 打开了一个连接并设置了我需要设置的请求 header 。

        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

在发出 GET 请求时,setDoOutput 应该被注释掉。

        con.setDoInput(true);
        con.setDoOutput(true); 
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestProperty("X-Cookie", "token=" + token);
        con.setRequestProperty("X-ApiKeys", "accessKey="+"23243;" +"secretKey="+"45543;");

这里我写入有效负载。

        //WRITING THE PAYLOAD to the http call
        OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
        writer.write(payload);
        writer.close();

在我写完有效负载后,我读取了我返回的任何响应(这取决于调用,当我进行文件下载(GET 请求)时,我没有读取响应,因为我已经读取了通过另一段代码响应)。

我希望这对可能遇到此线程的任何人有所帮助。

public String requestScan(int scan_Id, String token, String ID) throws MalformedInputException, ProtocolException, IOException {

    try {
        String endpoint = "https://host:port/scans/" + scan_Id + "/export?history_id=" ID;
        URL url = new URL(endpoint);

        String payload= "{\"format\" : \"csv\"}";

        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        con.setDoInput(true);
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestProperty("X-Cookie", "token=" + token);
        con.setRequestProperty("X-ApiKeys", "accessKey="+"324324;" + 
                "secretKey="+"43242;");

        //WRITING THE PAYLOAD to the http call
        OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
        writer.write(payload);
        writer.close();

        //READING RESPONSE
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        StringBuffer jsonString = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            jsonString.append(line);
        }
        br.close();
        con.disconnect();

        return jsonString.toString();
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    }
}

关于java - 在 Java REST 中为路径参数添加值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57903442/

相关文章:

javascript - 使用 JavaScript 调用 Laravel Controller 中的 POST 方法

java - 使用 Java SDK 查询 Azure 文件墙数据?

javascript - SharePoint Online REST - 通过 JavaScript/AJAX 上传图片

java - 将数据保存到 CouchDB 服务器的 HTTP PUT 请求 - Java Android?

java - Alfresco activi 5.* 或 6.* 中的自定义 Rest API

javascript - Access-Control-Allow-Headers 不允许请求 header 字段 Access-Control-Allow-Headers

java - 如何强制初始化 Hibernate JPA 代理以在 JSON 调用中使用它

Java MVC 和 Rest 服务器以及 JavaScript 重客户端

java - Android ArrayList,每行都有自定义数组

Wordpress:自动从推文和 YouTube 视频创建博客文章?