我试图从我的 Controller 调用第三方 api 来获取 token (POST 请求),但得到 400,我们正在使用 java.net.HttpURLConnection
我尝试添加使用的不同类型的 header ,但没有运气,我也尝试使用 RESTTemplate 但同样的问题。同样的情况也适用于第三方提供的 swagger UI,我在互联网上搜索并尝试了不同的解决方案,但没有成功。
public String getToken(String requestJsonString) {
String responseJSONString = "";
URL constructedURL = null;
HttpURLConnection httpConnection = null;
String url = null;
url = "any url"; //dummy
try {
constructedURL = new URL(url);
httpConnection = (HttpURLConnection) constructedURL.openConnection();
httpConnection.setDoOutput(Boolean.TRUE);
httpConnection.setRequestMethod(RaterConstants.POST);
httpConnection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
httpConnection.setRequestProperty("accept", RaterConstants.APPLICATION_JSON);
OutputStream os = httpConnection.getOutputStream();
os.write(requestJsonString.getBytes());
os.flush();
InputStream inputStream;
if (httpConnection.getResponseCode() >= 400) {
inputStream = httpConnection.getErrorStream();
} else {
inputStream = httpConnection.getInputStream();
}
BufferedReader br = new BufferedReader(new InputStreamReader((inputStream)));
String output;
while ((output = br.readLine()) != null) {
responseJSONString = output;
}
httpConnection.disconnect();
}catch (IOException e) {
logger.error("Error occurred in AccessTokenData : getToken : " + e.getCause());
}
return responseJSONString;
}
来自 swagger UI 的请求 header - 从开发工具获取
POST /Test HTTP/1.1
Host: host
Connection: keep-alive
Content-Length: 87
accept: application/json
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36
Sec-Fetch-Mode: cors
Content-Type: application/x-www-form-urlencoded
Origin: url
Sec-Fetch-Site: same-origin
Referer: url
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: PF=Ycbz2Gt6Bwyeguyegyue
requestJsonString 是正确的,因为我在 swagger 中尝试过,可能是请求 header 丢失,请用您的专业知识提供帮助。我预计会返回 200。
最佳答案
谢谢大家的回复。 根本原因:内容类型:application/x-www-form-urlencoded 不适用于 JSON。 我将 JSON 更改为普通字符串,并使用“&”作为分隔符,如下所示:
requestJsonString = "grant_type=abc&client_id=id_123&secret=demoSecret"
现在可以使用了
关于java - 使用httpurlconnection调用第三方api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57725595/