使用 Spring RestTemplate 发布带有对象的参数

Mat*_*ler 5 java spring json resttemplate

我正在尝试使用 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);
Run Code Online (Sandbox Code Playgroud)

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

{"username":[{"testuser"}],"password":[{"testpassword"}]}
Run Code Online (Sandbox Code Playgroud)

希望它们看起来如下:

username={"testuser"},password={"testpassword"}
Run Code Online (Sandbox Code Playgroud)

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

我究竟做错了什么?

Mat*_*ler 3

好吧,所以我最终在很大程度上弄清楚了这一点。我最终只编写了一个编组器/解组器,这样我就可以在更细粒度的级别上处理它。这是我的解决方案:

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);
Run Code Online (Sandbox Code Playgroud)

该解决方案使我能够控制对象的编组/解组方式,并简单地发布字符串,而不是允许 Spring 直接处理该对象。它的帮助很大!

  • marshalrequest 来源在哪里? (4认同)
  • 最好将 unmarshalResponse 代码放在这里并完成您的答案! (2认同)