我正在尝试使用API网址时从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);
}