簡體   English   中英

如何使用 Spring RestTemplate POST 表單數據?

[英]How to POST form data with Spring RestTemplate?

我想將以下(工作)curl 片段轉換為 RestTemplate 調用:

curl -i -X POST -d "email=first.last@example.com" https://app.example.com/hr/email

如何正確傳遞電子郵件參數? 以下代碼導致 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 );

我嘗試在 PostMan 中制定正確的調用,並且可以通過將 email 參數指定為正文中的“form-data”參數來使其正常工作。 在 RestTemplate 中實現此功能的正確方法是什么?

POST 方法應該與 HTTP 請求對象一起發送。 並且請求可能包含 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 );

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...-

如何在一個請求中發布混合數據:文件、字符串[]、字符串。

您可以只使用您需要的東西。

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;
}

POST 請求的正文和下一個結構中將包含 File:

POST https://my_url?array=your_value1&array=your_value2&name=bob 

這是使用 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());
    }

}

客戶端.java

@PostMapping(value = "/employee", consumes = "application/json")
public Employee createProducts(@RequestBody Employee product) {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<Employee> entity = new HttpEntity<Employee>(product,headers);

    ResponseEntity<Employee> response = restTemplate.exchange(
            "http://hello-server/rest/employee", HttpMethod.POST, entity, Employee.class);

    return response.getBody();
}

服務器端.java

private static List<Employee> list = new ArrayList<>();

@PostMapping(path="rest/employee", consumes = "application/json")
public Employee createEmployee(@RequestBody Employee employee)

{
    list.add(employee);
    return employee;
}
static
{
    list.add(new Employee(1, "albert", "Associate", "mphasis"));
    list.add(new Employee(2, "sachin", "software engineer", "mphasis"));
    list.add(new Employee(3, "dhilip", "Lead engineer", "IBM"));
}

雇員.java

public class Employee {

private Integer id;
private String name;
private String Designation;
private String company;
 // generate getter setter and toString()
}

1.發布請求在此處輸入圖片說明

您的url String需要為您傳遞的地圖使用變量標記,例如:

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

或者你可以顯式地將查詢參數編碼到字符串中以開始,而不必傳遞地圖,例如:

String url = "https://app.example.com/hr/email?email=first.last@example.com";

另請參見https://stackoverflow.com/a/47045624/1357094

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM