2017-05-15 18 views
0

次のコードでは、春にREST APIにHTTPのPOSTを行います奇妙な挙動は

URLがREST APIエンドポイントが含まれており、データはJSONをして文字列に変換され
... 
    HttpURLConnection connection = null; 
    InputStream input = null; 
    BufferedWriter output = null; 
    BufferedReader reader = null; 
    String result = null; 
    try { 
     connection = (HttpURLConnection) new URL(url).openConnection(); 
     connection.setRequestMethod("POST"); 
     connection.setDoOutput(true); 
     connection.setRequestProperty("Content-Type", "application/json"); 
     //Send data 
     output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); 
     output.write(data); 
     output.flush(); 
     //Read response 
     int responseCode = connection.getResponseCode(); 
     if (responseCode >= 400) { 
      input = connection.getErrorStream(); 
     } else { 
      input = connection.getInputStream(); 
     } 
     reader = new BufferedReader(new InputStreamReader(input)); 
     StringBuilder sb = new StringBuilder(); 
     String line; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line).append('\n'); 
     } 
     result = "Status " + responseCode + ".\n" + sb.toString(); 
     ... 

POSTで必要なユーザー属性。

問題は、POSTが正常に動作しますが、HTTPステータス201(HTTPステータス409などのエラーが発生した場合でも動作します)を取得した後、APIから返されたレスポンスボディを取得できないということです。不思議なことに、readline()関数は最初の読み取りで常にnullを返します。 APIはPostmanから完全に呼び出され、EclipseのJavaプロジェクトからそのコードを実行しても機能します。

は私のcompileSdkversiontargetSdkVersion私はこことそこに変更を適用し、ネットの周りHttpURLConnectionサンプルの多くの私のコードを比較した25

に設定されますが、ノー成功...

任意のアイデア?

+0

さらに別のサンプルをご覧ください:https://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection –

答えて

0

PostmanAndroid APPの両方から送信されたHTTPヘッダを比較した後、私は予想通り(Postmanが行うように)POSTリクエストにヘッダAccept: */*を添加することによって、それが働いたことに気づきました。 HTTP specificationによると、Acceptヘッダーフィールドのない要求は、ユーザーエージェントがすべてのメディアタイプを受け入れることを意味します。なので、Acceptヘッダーなしで動作している必要があります(同じAPIへのGETのように)。

私にとっては、Spring API側からのバグ、誤った設定、または「通常の」動作のようですが、それはAndroid HttpURLConnectionモジュールとは関係ありません。