RestTemplate实现HttpRequest请求

直接撸代码

@PostMapping("/certificate")
    public String certificate(String verSummary) throws JsonProcessingException {
        String url = "http://10.xx.xxx.xx:xxxx/SignServer/Sign";
        List list = new ArrayList();
        list.add(verSummary);

        Map req = new HashMap();
        req.put("VerSummary",list);
        String json = this.ObjectToJson(req);
        System.out.println("json is " + json);


        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type","application/json");
        HttpEntity httpEntity = new HttpEntity(json,headers);
        ResponseEntity res = this.restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);

        //ResponseEntity res = restTemplate.postForEntity( url, httpEntity , Map.class );
        Map cerResult = res.getBody();
        System.out.println("cerResult "+cerResult);
        String resultCode = (String)cerResult.get("ResultCode");
        return resultCode;
    }

其中,object转json的实现如下:

private final static ObjectMapper mapper = new ObjectMapper();
 
public String ObjectToJson(Object o) throws JsonProcessingException {
        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
        String json = ow.writeValueAsString(o);
        return json;
    }

你可能感兴趣的:(Java)