在邮递员api中工作正常,但在java中则不行

时间:2020-02-10 13:05:25

标签: java spring spring-boot api postman

我正在尝试使用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);
}

1 个答案:

答案 0 :(得分:1)

我有一个建议,邮递员可以为不同的编程语言生成请求的源代码,例如Java和JavaScript以及cURL之类的命令行工具。 我建议使用cURL为您提供更多详细信息,以帮助您进行连接配置。

enter image description here