2

有人可以告诉我如何发送带有原始数据参数的 POST 请求,如下图所示 在此处输入图像描述

我已经尝试了以下代码,但它不工作

HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
            JsonObject properties = new JsonObject();
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();         
            try {

                properties.addProperty("app_id", appId);
                properties.addProperty("identity","TestAPI");
                properties.addProperty("event", "TestCompleted");
                properties.addProperty("testType", t.getTestType());
                properties.addProperty("testName",t.getTestName());
                properties.addProperty("chapter","");
                properties.addProperty("module","");
                properties.addProperty("pattern",t.getTestPattern());
                HttpEntity<String> request = new HttpEntity<>(
                        properties.toString(), headers);
               // params.add("properties", properties.toString());
                 restTemplate.postForObject(url, request, String.class);

有人可以帮忙吗?

4

4 回答 4

2

尝试这个 :

@RestController
public class SampleController { 
    @RequestMapping("/req")
    public String performReqest(){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);        
        JsonObject properties = new JsonObject();
        properties.addProperty("no", "123");
        properties.addProperty("name", "stackoverflow");
        HttpEntity<String> request = new HttpEntity<>(properties.toString(), headers);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject("http://localhost:4040/student", request, String.class);
        return "Response from Server is : "+response;       
    }

    @RequestMapping("/student")
    public String consumeStudent(@RequestBody Student student){
        System.out.println(student);
        return "Hello.."+student.name;
    }   
}

class Student{
    public int no;
    public String name; 
    public Map<String,String> properties;   
}

不要忘记移动Student类并将所有字段更改为private需要 getter 和 setter。以上代码仅用于演示目的。

于 2018-05-04T10:44:16.760 回答
0

尝试这个:

URI uri = new URI("something");
Map<String, Object> params = new HashMap<>();
        params.put("app_id", "something");
        params.put("identity", something);

HttpEntity<Map<String, String>> request = new HttpEntity(params , headers);
   
ResponseEntity<String> response = restTemplate.postForEntity(uri, request, String.class);
于 2022-01-09T07:10:45.567 回答
0

请试试这个:

ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
于 2018-05-04T09:34:02.130 回答
0

您是否尝试过使用 postmaster 并首先检查输出。如果它工作,那么你可以去邮寄或交换方法。交换退货并邮寄不要。

于 2018-05-04T10:01:29.160 回答