3

REST を初めて使用し、JSON 文字列を REST リクエスト URL のパス変数として送信しようとしています。クライアントからリクエストを送信するために行っていること:

JSONObject json = new JSONObject();
try {
    json.put("Test", "123");
    json.put("tracks", "1234");
    jj = json.toString();
} catch (JSONException e1) {
    // TODO Auto-generated catch block
       e1.printStackTrace();
}

   String url =  "http://localhost:8090/webApp/restresource/"+jj+".do";
   st = (String) restTemplate.postForObject(url,jj, String.class, jj);

残りのサーバー:

@RequestMapping(value = "/restresource/{code}", method=RequestMethod.POST, consumes= "application/json")
public @ResponseBody String useJson(@PathVariable String jj) {

    String result;

    JSONObject jObject = new JSONObject();
    try {
        result = jObject.getJSONObject(jj).toString();

    } catch (JSONException jse) {
        jse.printStackTrace();
    }

return result;

}

私が得る例外はnot enough variable values to expand "Test"

編集:私のリクエストURLは次のようになります:

http://localhost:8090/app/restResource/%7B%22%22:%22123%22,%22tracks%22:%221234%22%7D.do

HttpClientErrorException も見ました! どんな助けでも大歓迎です!

4

2 に答える 2

0

私がすることは:

HttpEntity<Object> entity = new HttpEntity<Object>(json); // Create HTTP Entity to post to rest endpoint
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.postForEntity(url, entity, Object.class);

サーバー側では、これを PathVariable としてアクセスする必要はなく、代わりに使用できます

@RequestMapping(value = "/restresource", method=RequestMethod.POST, consumes= "application/json")
public @ResponseBody String useJson(@RequestBody JSonObject object) {

したがって、Spring フレームワークは、json 文字列を指定されたオブジェクト タイプに自動的に変換します。それに応じて URL を調整し、再試行できます。

于 2013-10-14T14:13:42.490 に答える
0

以下で使用できます

 <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <property name="messageConverters">
        <list>     
             <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
        </list>
    </property>
</bean>



<dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.7.1</version>
</dependency>

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>org.springframework.web</artifactId>
        <version>3.1.1.RELEASE</version>
</dependency>
于 2013-10-15T04:38:00.813 に答える