我想发送POST请求到这个特定的API:https://developer.lufthansa.com/docs/read/api_basics/Getting_Started,我研究了如何做到这一点,并尝试了一切,但它根本无法工作,我总是得到HTTP 400或HTTP 401错误。这里是我的代码:HttpsURLConnection - 发送POST请求
private void setAccessToken(String clientID, String clientSecret) {
try {
URL url = new URL(URL_BASE + "oauth/token");
String params = "client_id=" + clientID + "&client_secret=" + clientSecret + "&grant_type=client_credentials";
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write(params);
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch(IOException e) {
e.printStackTrace();
}
}
Kenta1561
HTTP 400/401错误表明服务器拒绝你的请求。 – MultiplyByZer0
401未经授权......您是否考虑过使用OkHttp? –
@ cricket_007我不知道他们是否必须成为身体的一部分,网站只是声明参数是'POST参数'。它适用于Android,如果我这样做:String query = new Uri.Builder() .appendQueryParameter(“client_id”,params [0]) .appendQueryParameter(“client_secret”,params [1]) .appendQueryParameter(“grant_type “, ”client_credentials“) .build() .getEncodedQuery();但在这里它不起作用。 – Kenta1561