Java 如何使用 Spring RestTemplate 在 POST 中传递数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19940002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can you pass an array in a POST with Spring RestTemplate?
提问by Joe
I am having difficulty passing an array in a POST using Spring's RestTemplate. The following is my code that I am using:
我无法使用 Spring 的 RestTemplate 在 POST 中传递数组。以下是我正在使用的代码:
I am calling the RestTemplate here:
我在这里调用 RestTemplate:
private static void sendEntries() {
RestTemplate restTemplate = new RestTemplate();
String uri = "http://localhost:8080/api/log/list.json";
// Both LogEntry and ExceptionEntry extend Entry
LogEntry entry1 = new LogEntry();
ExceptionException entry2 = new ExceptionEntry();
Entry[] entries = {entry1, entry2};
entries = restTemplate.postForObject(uri, entries, Entry[].class);
System.out.println(new Gson().toJson(entries));
}
And the Controller contains:
控制器包含:
@RequestMapping(value = "api/log/list", method = RequestMethod.POST)
public @ResponseBody Entry[] saveList(@RequestBody Entry[] entries) {
for (Entry entry : entries) {
entry = save(entry);
}
return entries;
}
This results in a:
这导致:
org.springframework.web.client.HttpClientErrorException: 400 Bad Request
It doesn't look like the array is being added to the request. All other POST request work when I am not trying to pass an array. I am just not sure what I need to do to get the array to pass over properly.
看起来数组没有被添加到请求中。当我不尝试传递数组时,所有其他 POST 请求都有效。我只是不确定我需要做什么才能让数组正确传递。
Is this the proper way of doing it? Is it possible to pass a Collection instead?
这是正确的做法吗?是否可以通过 Collection 代替?
采纳答案by vtokmak
You can check this post: How to pass List or String array to getForObject with Spring RestTemplate, solution for that post is:
您可以查看这篇文章:How to pass List or String array to getForObject with Spring RestTemplate,该帖子的解决方案是:
List or other type of objects can post with RestTemplate's postForObject method. My solution is like below:
列表或其他类型的对象可以使用 RestTemplate 的 postForObject 方法发布。我的解决方案如下:
controller:
控制器:
@RequestMapping(value="/getLocationInformations", method=RequestMethod.POST)
@ResponseBody
public LocationInfoObject getLocationInformations(@RequestBody RequestObject requestObject)
{
// code block
}
Create a request object for posting to service:
创建一个用于发布到服务的请求对象:
public class RequestObject implements Serializable
{
public List<Point> pointList = null;
}
public class Point
{
public Float latitude = null;
public Float longitude = null;
}
Create a response object to get values from service:
创建一个响应对象以从服务中获取值:
public class ResponseObject implements Serializable
{
public Boolean success = false;
public Integer statusCode = null;
public String status = null;
public LocationInfoObject locationInfo = null;
}
Post point list with request object and get response object from service:
带有请求对象的发布点列表并从服务中获取响应对象:
String apiUrl = "http://api.website.com/service/getLocationInformations";
RequestObject requestObject = new RequestObject();
// create pointList and add to requestObject
requestObject.setPointList(pointList);
RestTemplate restTemplate = new RestTemplate();
ResponseObject response = restTemplate.postForObject(apiUrl, requestObject, ResponseObject.class);
// response.getSuccess(), response.getStatusCode(), response.getStatus(), response.getLocationInfo() can be used
回答by Yuliia Ashomok
How to POST array:
如何POST数组:
private String doPOST(String[] array) {
RestTemplate restTemplate = new RestTemplate(true);
//add array
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
for (String item : array) {
builder.queryParam("array", item);
}
//another staff
String result = "";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
new HttpEntity<>(headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
builder.build().encode().toUri(),
HttpMethod.POST,
requestEntity,
String.class);
HttpStatus statusCode = responseEntity.getStatusCode();
if (statusCode == HttpStatus.ACCEPTED) {
result = responseEntity.getBody();
}
return result;
}
The POST request will have next structure:
POST 请求将具有下一个结构:
POST https://my_url?array=your_value1&array=your_value2
On Server side:
在服务器端:
public class MyServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest req, HttpServletResponse response) {
try {
String[] array = req.getParameterValues("array");
String result = doStaff(array);
response.getWriter().write(result);
response.setStatus(HttpServletResponse.SC_ACCEPTED);
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
}
}