2017-04-11 284 views
0

我想发送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

+0

HTTP 400/401错误表明服务器拒绝你的请求。 – MultiplyByZer0

+0

401未经授权......您是否考虑过使用OkHttp? –

+0

@ 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

回答

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"} 
+0

我仍然不知道为什么会发生这种情况,当我使用OkHttp时,一切正常,因此我的客户端ID和客户端密码正确无误。尽管如此,谢谢你的回答。 – Kenta1561