简体   繁体   English

使用Java消费Rest API

[英]Consuming Rest API using java

I have code a java script to consume API response. 我有一个Java脚本代码来使用API​​响应。 But I am getting a bad request whenever I am trying to run it. 但是,每当我尝试运行它时,我都会收到一个错误的请求。 Kindly help me how to consume API through java. 请帮助我如何通过Java使用API​​。

Here I am trying to generate JWT token.... Please find the code below.. 在这里,我正在尝试生成JWT令牌。...请在下面找到代码。

public static void main(String[] args) throws Exception {
    URL url = new URL("URL");


    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.connect();
    try {



        String jsonData1 = "{\"grant_type\":\"aksa\"}";
        String jsonData2 = "{\"username\":\"dkssdsk\"}";
        String jsonData3 = "{\"password\":\"xE2w04kC1a7S\"}";
        String jsonData4 = "{\"scope\":\"mksssl,/\"}";


        DataOutputStream output = new DataOutputStream(connection.getOutputStream());
              output.write(jsonData1.getBytes());
              output.write(jsonData2.getBytes());
              output.write(jsonData3.getBytes());
              output.write(jsonData4.getBytes());``
              output.flush();

              System.out.println(output);


        // Read the response:
       BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));`enter code here`

        String line;


        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    } catch (Exception e) {

        System.out.println(e.getMessage());
    }

    System.out.println("Response code:" + connection.getResponseCode());
    System.out.println("Response message:" + connection.getResponseMessage());
}
}

Your code writes: 您的代码写道:

{"grant_type":"aksa"}
{"username":"dkssdsk"}
{"password":"xE2w04kC1a7S"}
{"scope":"mksssl,/"}

This is not valid JSON. 这是无效的JSON。 There are many JSON validators (including web pages you can copy/paste into) you could use to show this. 您可以使用许多JSON验证程序(包括可以复制/粘贴到的网页)来显示此信息。

Test your service using a tool such as Postman. 使用邮递员之类的工具测试您的服务。 Once you have it working, ensure that your program writes the same content as the body configured in Postman. 一旦工作,请确保程序写入与Postman中配置的正文相同的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM