【发布时间】:2020-05-25 19:28:26
【问题描述】:
我试图在使用 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);
}
【问题讨论】:
-
那 19 个标题是什么?
-
@FedericoklezCulloca 回应
-
好的,那你为什么向我们显示响应而不是请求?
-
Spring Boot 不是自带了一个合理的 HTTP 客户端,这样你就不用写 20 行代码来做一个简单的 GET 请求了吗?
标签: java spring spring-boot api postman