使用java消费restapi
我编写了一个java脚本来使用API响应。但每当我尝试运行它时,都会收到一个错误的请求。 请帮助我如何通过java使用API 在这里,我试图生成JWT令牌。。。。 请在下面查找代码使用java消费restapi,java,Java,我编写了一个java脚本来使用API响应。但每当我尝试运行它时,都会收到一个错误的请求。 请帮助我如何通过java使用API 在这里,我试图生成JWT令牌。。。。 请在下面查找代码 public static void main(String[] args) throws Exception { URL url = new URL("URL"); HttpURLConnection connection = (HttpURLConnection) url.openConnec
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());
}
}
你的代码写:
{"grant_type":"aksa"}
{"username":"dkssdsk"}
{"password":"xE2w04kC1a7S"}
{"scope":"mksssl,/"}
这不是有效的JSON。可以使用许多JSON验证器(包括可以复制/粘贴到的网页)来显示这一点
使用诸如Postman之类的工具测试您的服务。一旦你让它工作,确保你的程序写的内容与Postman中配置的正文相同。是的,我已经在Postman中测试过了,它工作正常。你能给我发送一些JSON验证程序的链接吗