2017-02-20 3 views
1

いくつかのJSONデータをRESTfulスプリングコントローラにPOSTしようとしています。しかし、応答ステータスとして「400 Bad Request」を取得する。400 Bad Request - JSONデータをRESTfulコントローラにポストするとき

のpom.xmlの依存関係:

enter code here <properties> 
    <org.springframework-version>4.1.4.RELEASE</org.springframework-version> 
</properties> 

<!-- Spring --> 
<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-context</artifactId> 
    <version>${org.springframework-version}</version> 
    <exclusions> 
     <!-- Exclude Commons Logging in favor of SLF4j --> 
     <exclusion> 
      <groupId>commons-logging</groupId> 
      <artifactId>commons-logging</artifactId> 
     </exclusion> 
    </exclusions> 
</dependency> 
<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-webmvc</artifactId> 
    <version>${org.springframework-version}</version> 
</dependency> 

<!-- Servlet --> 
<dependency> 
    <groupId>javax.servlet</groupId> 
    <artifactId>servlet-api</artifactId> 
    <version>2.5</version> 
    <scope>provided</scope> 
</dependency> 
<dependency> 
    <groupId>javax.servlet.jsp</groupId> 
    <artifactId>jsp-api</artifactId> 
    <version>2.1</version> 
    <scope>provided</scope> 
</dependency> 
<dependency> 
    <groupId>javax.servlet</groupId> 
    <artifactId>jstl</artifactId> 
    <version>1.2</version> 
</dependency> 

<!-- json --> 
<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-core</artifactId> 
    <version>2.4.1</version> 
</dependency> 
<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-databind</artifactId> 
    <version>2.4.1.1</version> 
</dependency> 
<dependency> 
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-core-asl</artifactId> 
    <version>1.9.13</version> 
</dependency> 
<dependency> 
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-mapper-asl</artifactId> 
    <version>1.9.13</version> 
</dependency> 

ディスパッチャ-servlet.xml:

<beans:bean 
    class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> 
    <beans:property name="messageConverters"> 
     <beans:list> 
      <beans:ref bean="jsonConverter" /> 
      <!-- <ref bean="marshallingConverter" /> <ref bean="atomConverter" /> --> 
     </beans:list> 
    </beans:property> 
</beans:bean> 

<beans:bean id="jsonConverter" 
    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> 
    <beans:property name="supportedMediaTypes" value="application/json" /> 
</beans:bean> 

Controllerクラス私はこのために使用していますキーの設定ファイルからコードの下に与える

@Controller 
@RequestMapping("/api/beacons") 
public class APIController { 

    private static final Logger logger = LoggerFactory.getLogger(APIController.class); 

    @Autowired 
    BeaconService beaconService; 

    @RequestMapping(method = RequestMethod.GET, produces = "application/json") 
    @ResponseBody 
    public List<BeaconVO> listAllBeacons() { 
     logger.info("/api/beacon GET"); 
     List beacons = beaconService.findList(new BeaconVO()); 
     return beacons; 
    } 

    @RequestMapping(method = RequestMethod.POST, consumes = "application/json") 
    // @ResponseStatus(HttpStatus.NO_CONTENT) 
    @ResponseBody 
    public BeaconVO saveBeacon(@RequestBody BeaconVO beaconVO) { 
     logger.info("/api/beacon POST"); 
     beaconService.register(beaconVO); 
     return beaconVO; 
    } 

のリクエスト詳細:

URL:http: // localhost:8080/test/api/beacons 

    Method: 
    POST 

    Headers:Accept:application/ 
    json 

    Payload: 

{ 
    "no": 1 , 
    "uuid": "123" 
    } 

BeaconVO:

public class BeaconVO { 

private int no; 

private String uuid; 

public int getNo() { 
    return no; 
} 

public void setNo(int no) { 
    this.no = no; 
} 

public String getUuid() { 
    return uuid; 
} 

public void setUuid(String uuid) { 
    this.uuid = uuid; 
} 

}

クライアントコード(アンドロイド)

public class MainActivity extends Activity { 
private static final String URL = "http://192.168.1.24:8080/test/api/beacons"; 
Button btnGet, btnPost; 
TextView tv; 

JSONObject json; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    btnGet = (Button) findViewById(R.id.btnGet); 
    btnPost = (Button) findViewById(R.id.btnPost); 
    tv = (TextView) findViewById(R.id.tv); 

    btnGet.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      new Thread(new Runnable() { 

       @Override 
       public void run() { 
        // TODO Auto-generated method stub 
        try { 
         String jsonData = getJSONData(URL, "GET"); 
         if (jsonData == null || jsonData.isEmpty()) { 
          return; 
         } 
         JSONArray jsonArray = new JSONArray(jsonData); 
         json = jsonArray.getJSONObject(0); 
         StringBuilder sb = new StringBuilder(); 
         sb.append("no/UUID\n"); 
         for (int i = 0; i < jsonArray.length(); i++) { 

          JSONObject jsonObject = (JSONObject) jsonArray.get(i); 

          sb.append(jsonObject.getString("no") + "/" + jsonObject.getString("uuid")); 
          sb.append("\n"); 

         } 
         setText(json.toString(), false); 
        } catch (JSONException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
         setText(e.toString(), true); 
        } 
       } 
      }).start(); 

     } 
    }); 

    btnPost.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      new Thread(new Runnable() { 

       @Override 
       public void run() { 
        // setJSONData(URL, "POST", json.toString()); 
        POST(URL, json.toString()); 
       } 
      }).start(); 
     } 
    }); 
} 


public void POST(String strUrl, String jsonData) { 
    try { 
     URL url = new URL(strUrl); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setConnectTimeout(5000);// 5 secs 
     connection.setReadTimeout(5000);// 5 secs 

     connection.setRequestMethod("POST"); 
     connection.setDoOutput(true); 
     connection.setRequestProperty("Content-Type", "application/json"); 

     InputStream is = null; 
     int status = connection.getResponseCode(); 
     if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { 
      is = connection.getErrorStream(); 
     } else { 
      is = connection.getInputStream(); 
     } 
     if (connection.getResponseCode() != 200) { 
      throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode()); 
     } 
     OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); 

     out.write(jsonData); 
     out.flush(); 
     out.close(); 

     BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
     String line = null; 
     while ((line = br.readLine()) != null) { 
      System.out.println(line); 
     } 
     connection.disconnect(); 
    } catch (Exception e) { 
     // TODO: handle exception 
     e.printStackTrace(); 
     setText(e.toString(), true); 
    } 
} 

private String getJSONData(String url, String method) { 
    try { 
     InputStream is = getInputStream(url, method); 
     BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 
     int bufferSize = 1024 * 1024; 
     char[] readBuf = new char[bufferSize]; 
     int resultSize = 0; 
     while ((resultSize = br.read(readBuf)) != -1) { 
      if (resultSize == bufferSize) { 
       sb.append(readBuf); 
      } else { 
       for (int i = 0; i < resultSize; i++) { 
        sb.append(readBuf[i]); 
       } 
      } 
     } 
     final String jsonData = sb.toString(); 
     setText(jsonData, false); 

     is.close(); 
     return jsonData; 
    } catch (Exception e) { 
     e.printStackTrace(); 
     setText(e.toString(), true); 
     return null; 
    } 
} 


private InputStream getInputStream(String strUrl, String method) { 
    InputStream is; 
    try { 
     log("getInputStream(" + strUrl + ", " + method + ")"); 
     URL url = new URL(strUrl); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 

     connection.setRequestMethod(method); 
     connection.setRequestProperty("Accept", "application/json"); 

     int status = connection.getResponseCode(); 
     if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { 
      is = connection.getErrorStream(); 
     } else { 
      is = connection.getInputStream(); 
     } 
     if (connection.getResponseCode() != 200) { 
      throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode()); 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
     setText(e.toString(), true); 
     return null; 
    } 
    return is; 
} 

StringBuilder sb = new StringBuilder(); 

private void setText(final String msg, final boolean isError) { 
    runOnUiThread(new Runnable() { 

     @Override 
     public void run() { 
      if (isError) { 
       sb.append(msg); 
       sb.append("\n"); 
       tv.setText("\n-------------------\n"+sb.toString()); 
      } else { 
       tv.setText(msg); 
      } 
     } 
    }); 
} 

}

私を助けてください。

+0

GETリクエストは機能しますか? BeaconVOクラスを表示できますか?ログにはさらに情報が必要です。 – Maddy

+0

あなたはリクエストに 'Content-Type'ヘッダがないと思います。 'Content-Type:application/json' – Titus

+0

GET要求はうまくいきます。私はBeaconVOを追加します – onesang

答えて

-2

ペイロード本体は、おそらくBeaconVOオブジェクトに設定(マッピング)できません。

+0

私はすでにBeaconVOフィールドをチェックしています。 @RequestBodyを削除してみますが、応答ステータスとして「500 Bad Request」を取得してみてください。 – onesang

+1

JSONをこのオブジェクトにマップすることはできません。 ペイロード{"いいえ":1 "uuid": "123"}にカンマ(「1」の後に)が必要です。 – MicD

+0

jsonと欠落しているヘッダーのコンマがないことを除いてContent-Type:application/jsonはコメントで指摘されていますが、これはうまく動作します – Maddy

関連する問題