2017-08-16 31 views
0

gssを使用してHashMapに変換しているPOST JSON文字列だけを受け取るspringbootプロジェクトがあります。私はPostmanをPOSTとしてテストし、本体をpropsとして{'fistname': 'John', 'lastname' : 'Doe'}のようなjson文字列で追加して、props = {'fistname': 'John', 'lastname' : 'Doe'}に変換します。一方予想Java RESTクライアントを作成して春のブートREST APIを呼び出します

@RequestMapping(value = "/rest", method = RequestMethod.POST) 
    protected String parse(@RequestParam("props") String props) { 
    Gson gson = new Gson(); 
    Map<String, String> params = new HashMap<String, String>(); 
    params = gson.fromJson(props, Map.class); 

    // Rest of the process 
} 

としてその作業は、私がFailed :: HTTP error code : 400を得る

protected void callREST() { 

     try { 
      String json = someClass.getDate() //retrieved from database which is stored as json structure 
      Map<String, String> props = gson.fromJson(json, Map.class); 

      URL url = new URL("http://localhost:9090/myApp/rest"); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setDoOutput(true); 
      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("Content-Type", "application/json"); 

      DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); 

      System.out.println(props.toString()); 
      wr.writeBytes(json.toString()); 
      wr.flush(); 
      wr.close(); 
      if(conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { 
       throw new RuntimeException("Failed :: HTTP error code : " + conn.getResponseCode()); 
      } 

      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      String output; 
      System.out.println("Output from Server ... \n"); 
      while((output = br.readLine()) != null) { 
       System.out.println(output); 
      } 

      conn.disconnect(); 

     } catch(Exception e) { 
      //print stack trace 
     } 
} 

このAPIを呼び出す必要のJavaEEプロジェクトを、持っています。私は、その春の起動は、props変数のデータを受信して​​いないと思っています。 この呼び出しを成功させるために、プロップとデータを渡すためにクライアントコードに何を追加する必要がありますか?

注:9090

+1

Springの 'RestTemplate'クラスを見てください。これは非常に便利です。 – Berger

答えて

1

@RequestParamは、サーバがリクエストURL http://localhost:9090/myApp/rest?param=.....でのparamをお待ちしていますが、あなたのクライアントにあなたがでJSONを書いていることを意味します、Springbootは 異なるTomcat上で実行されている8080:JavaEEのは、Tomcat上で実行されています要求の本体。

値はJSONであることを起こるあなたのエンドポイントで@RequestBody注釈

protected String parse(@RequestBody String props) {...} 
+0

どうすれば非同期化できますか? – user525146

1

あなたのリソースを使用しようとする(x-www-form-urlencodedでのエンコードを使用して、すなわち、キーと値のペア、)フォームパラメータを取得する予定は、 (投稿した内容は有効なJSONではありません)。

クライアントのJavaコードでは、コンテンツタイプをapplication/jsonに設定し、JSONをx-www-form-urlencodedボディのキー "props"の値として送信するのではなく、本体として送信します。

これは動作しません。

サーバーを変更できる場合は、それを行います。直接体としてJSONを受け入れ:

@RequestMapping(value = "/rest", method = RequestMethod.POST) 
public String parse(@RequestBody Map<String, String> map) { 
    ... 
} 

ない場合は、正しいキーと値のペアを送信する必要があり、その値が正しくURLエンコードであることを確認します。

関連する問題