我尝试在使用 API Url 时从 API 获取 JSON 对象。当我在 Postman 中测试它时,效果非常好,但是当我在 Spring 应用程序中尝试它时,它返回 405 消息(请求的 URL 不允许该方法)
我的Java代码:-
URL tokenURL = new URL("https://something.in/v1/token");
HttpURLConnection tokenConnection = (HttpURLConnection) tokenURL.openConnection();
tokenConnection.setRequestMethod("GET");
tokenConnection.setConnectTimeout(Integer.parseInt(env.getProperty
("common.webServiceCall.maxTimeOut")));
tokenConnection.setReadTimeout(Integer.parseInt(env.getProperty
("common.webServiceCall.maxTimeOut")));
tokenConnection.setRequestProperty("Content-Type", "application/json");
tokenConnection.setRequestProperty("Accept", "application/json");
tokenConnection.setRequestProperty("X-IBM-Client-Id", "45878d21-469c-b68e-34b1suds34c");
tokenConnection.setRequestProperty("X-IBM-Client-Secret", "ytGThJH4sW7hY2skhJHG65uC7xH7v645fsdfkjgFGHDFgcvhg");
tokenConnection.setDoInput(true);
tokenConnection.setDoOutput(true);
OutputStream tokenStream = null;
try {
tokenStream = tokenConnection.getOutputStream();
} catch (RemoteException e) {
e.printStackTrace();
}
try {
for(int i = 0; i < 3; i++) {
tokenConnection.connect();
if (tokenConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (tokenConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((tokenConnection.getInputStream())));
StringBuilder serviceResponse = new StringBuilder();
String serviceResponseLine;
while ((serviceResponseLine = bufferedReader.readLine()) != null) {
serviceResponse.append(serviceResponseLine);
}
tokenStream.close();
tokenConnection.disconnect();
System.out.println(serviceResponse);
} else {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((tokenConnection.getErrorStream())));
StringBuilder serviceResponse = new StringBuilder();
String serviceResponseLine;
while ((serviceResponseLine = bufferedReader.readLine()) != null) {
serviceResponse.append(serviceResponseLine);
}
tokenStream.close();
tokenConnection.disconnect();
System.out.println(serviceResponse);
}
最佳答案
我有一个建议, postman 可以为不同的编程语言生成请求的源代码,例如java 和 JavaScript 以及 cURL 等命令行工具。 我建议使用 cURL 为您提供更详细的详细信息,可以帮助您进行连接配置。
关于java - 在 postman api 中工作正常,但在 java 中则不然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60151078/