【问题标题】:Using Spring RestTemplate to POST params with objects使用 Spring RestTemplate 发布带有对象的参数
【发布时间】:2014-09-22 21:49:15
【问题描述】:

我正在尝试使用 Spring 的 RestTemplate 功能发送 POST 请求,但在发送对象时遇到问题。这是我用来发送请求的代码:

RestTemplate rt = new RestTemplate();

MultiValueMap<String,Object> parameters = new LinkedMultiValueMap<String,Object>();
parameters.add("username", usernameObj);
parameters.add("password", passwordObj);

MyReturnObj ret = rt.postForObject(endpoint, parameters, MyRequestObj.class);

我还有一个日志拦截器,所以我可以调试输入参数,它们几乎是正确的!目前,usernameObjpasswordObj 参数显示如下:

{"username":[{"testuser"}],"password":[{"testpassword"}]}

希望它们的外观如下:

username={"testuser"},password={"testpassword"}

假设 usernameObjpasswordObj 是已编组为 JSON 的 Java 对象。

我做错了什么?

【问题讨论】:

    标签: java json spring resttemplate


    【解决方案1】:

    好的,所以我最终解决了这个问题,大部分情况下。我最终只写了一个编组器/解组器,这样我就可以在更细粒度的级别上处理它。这是我的解决方案:

    RestTemplate rt = new RestTemplate();
    
    // Create a multimap to hold the named parameters
    MultiValueMap<String,String> parameters = new LinkedMultiValueMap<String,String>();
    parameters.add("username", marshalRequest(usernameObj));
    parameters.add("password", marshalRequest(passwordObj));
    
    // Create the http entity for the request
    HttpEntity<MultiValueMap<String,String>> entity =
                new HttpEntity<MultiValueMap<String, String>>(parameters, headers);
    
    // Get the response as a string
    String response = rt.postForObject(endpoint, entity, String.class);
    
    // Unmarshal the response back to the expected object
    MyReturnObj obj = (MyReturnObj) unmarshalResponse(response);
    

    这个解决方案让我可以控制对象的编组/解组方式,并简单地发布字符串,而不是让 Spring 直接处理对象。它的帮助很大!

    【讨论】:

    • marshalrequest 源在哪里?
    • 最好把 unmarshalResponse 代码放在这里,完成你的答案!
    【解决方案2】:

    对于客户端

    要将对象作为 json 字符串传递,请使用 MappingJackson2HttpMessageConverter

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    

    服务器端spring配置

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonMessageConverter"/>
            </list>
        </property>
    </bean>
    <bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
    

    【讨论】:

    • 感谢您的回复,但我已经尝试过了,但没有成功。如您所见,请求以 JSON 格式发送,但包含在名称与参数名称相同的 JSON 对象中。我不希望我的 JSON 字符串被这样括起来。
    猜你喜欢
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 2016-03-10
    • 2021-08-12
    • 2012-01-07
    • 1970-01-01
    • 2017-10-30
    相关资源
    最近更新 更多