如何使用Spring RestTemplate发布表单数据?

sim*_*sim 124 java rest spring resttemplate

我想将以下(工作)curl片段转换为RestTemplate调用:

curl -i -X POST -d "email=first.last@example.com" https://app.example.com/hr/email
Run Code Online (Sandbox Code Playgroud)

如何正确传递电子邮件参数?以下代码导致404 Not Found响应:

String url = "https://app.example.com/hr/email";

Map<String, String> params = new HashMap<String, String>();
params.put("email", "first.last@example.com");

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity( url, params, String.class );
Run Code Online (Sandbox Code Playgroud)

我试图在PostMan中制定正确的调用,我可以通过将body参数指定为正文中的"form-data"参数来使其正常工作.在RestTemplate中实现此功能的正确方法是什么?

Tha*_*mar 296

应该沿HTTP请求对象发送POST方法.并且请求可以包含HTTP标头或HTTP主体或两者.

因此,让我们创建一个HTTP实体,并在正文中发送标题和参数.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "first.last@example.com");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
Run Code Online (Sandbox Code Playgroud)

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#postForObject-java.lang.String-java.lang.Object-java.lang.类java.lang.Object继承...-

  • `ResponseEntity&lt;String&gt; response = new RestTemplate().postForEntity(url, request, String.class);` 我收到 `org.springframework.http.converter.HttpMessageNotWritableExc‌​eption:无法写入内容:找不到类的序列化器java.util.Collections$3` (2认同)
  • 因此,这仅适用于字符串...如果要在有效载荷中发送Java对象怎么办? (2认同)

Yul*_*mok 18

如何在一个请求中POST混合数据:File,String [],String.

您只能使用您需要的东西.

private String doPOST(File file, String[] array, String name) {
    RestTemplate restTemplate = new RestTemplate(true);

    //add file
    LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("file", new FileSystemResource(file));

    //add array
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
    for (String item : array) {
        builder.queryParam("array", item);
    }

    //add some String
    builder.queryParam("name", name);

    //another staff
    String result = "";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
            new HttpEntity<>(params, 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;
}
Run Code Online (Sandbox Code Playgroud)

POST请求将在其Body和下一个结构中包含File:

POST https://my_url?array=your_value1&array=your_value2&name=bob 
Run Code Online (Sandbox Code Playgroud)


Piy*_*tal 7

这是使用spring的RestTemplate进行POST休息调用的完整程序.

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.ituple.common.dto.ServiceResponse;

   public class PostRequestMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        Map map = new HashMap<String, String>();
        map.put("Content-Type", "application/json");

        headers.setAll(map);

        Map req_payload = new HashMap();
        req_payload.put("name", "piyush");

        HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
        String url = "http://localhost:8080/xxx/xxx/";

        ResponseEntity<?> response = new RestTemplate().postForEntity(url, request, String.class);
        ServiceResponse entityResponse = (ServiceResponse) response.getBody();
        System.out.println(entityResponse.getData());
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 发布application/json而不是表单数据 (5认同)
  • 如果将 `application/json` 内容类型替换为 `application/x-www-form-urlencoded`,您将得到 _org.springframework.web.client.RestClientException: No HttpMessageConverter for java.util.HashMap and content type "application /x-www-form-urlencoded"_ - 请参阅 /sf/ask/2193998901/ (2认同)