HttpsURLConnection - 发送POST请求

时间:2017-04-11 16:55:45

标签: java http

我想向此特定API发送POST请求:https://developer.lufthansa.com/docs/read/api_basics/Getting_Started我研究了如何做并尝试了所有内容,但它根本不起作用,我总是得到HTTP 400或HTTP 401错误。这是我的代码:

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

1 个答案:

答案 0 :(得分:0)

似乎您的代码运行良好,可能是您提供无效的clientID或clientSecret,以便您在这种情况下得到错误的响应(因为401表示未经授权)。您可以做的一件事是,如果http请求状态正常(200),您只会收到响应消息。如果是400或401 http响应状态,您也可能会收到无效的响应消息。要打印无效的回复消息,您可以按照以下代码进行操作:

private void setAccessToken(String clientID, String clientSecret) throws Exception {

    String params = "client_id=" + clientID + "&client_secret=" + clientSecret + "&grant_type=client_credentials";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    BufferedReader in;
    // add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(params);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    if (responseCode >= 400)
        in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
    else 
        in = new BufferedReader(new InputStreamReader(con.getInputStream()));

    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    System.out.println(response.toString());
}

通过这种方式,您还可以获得无效的响应消息。在你的情况下,当我试图点击提供的API时,它给出了以下回复:

{"error": "invalid_client"}