使用 Spring REST 模板发布 JSON 对象

问题描述 投票:0回答:1

我正在使用 Spring Rest 模板发布 JSON 对象。它适用于较少的数据,但发布更多的数据会引发请求 URI 太长错误。

       final String url = getServiceUrl() + "/rs/doc?param1=test";

        RestTemplate restTemp=getRestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);

        //set your entity to send
        HttpEntity<MyBean> request = new HttpEntity<MyBean>(myBean,headers);

        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        messageConverters.add(new MappingJacksonHttpMessageConverter());
        messageConverters.add(new FormHttpMessageConverter());
        restTemp.getMessageConverters().addAll(messageConverters);

        // send it!
        responseEntity = restTemp.exchange(url, HttpMethod.POST, request, String.class);

请求正文应在 POST 方法中接受无限数据。但这似乎在这里不起作用。有人可以指导吗?

json spring rest spring-mvc spring-rest
1个回答
0
投票

下面对我来说效果很好。我已在标头和需要发送的帖子参数中添加了安全详细信息。

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.set(ApplicationConstants.API_KEY, ApplicationConstants.TEST_API_KEY_VALUE);
headers.set(ApplicationConstants.AUTH_TOKEN, ApplicationConstants.TEST_API_TOKEN_VALUE);
MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
postParameters.add("purpose", cust.getPaymentPurpose());
postParameters.add("buyer_name", cust.getCustomerName());
postParameters.add("email", cust.getCustomerEmailId());
postParameters.add("phone", cust.getCustomerMobNum());
postParameters.add("send_email", "False");
postParameters.add("send_sms", "False");
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(postParameters, headers);
ResponseEntity<String> result = restTemplate.exchange("YOUR URL", HttpMethod.POST, requestEntity, String.class);
OnlinePaymentModel paymentModel = gson.fromJson(result.getBody(), OnlinePaymentModel.class);
© www.soinside.com 2019 - 2024. All rights reserved.