兵兵有你

人品好,气质差.丢了工作就回家...

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;



    public String doGet(String url){
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> resp = restTemplate.getForEntity(url,String.class);
        return resp.getBody();
    }

    //formdata post请求
    public String doPost(String queryUrl, HashMap<String,Object> queryParam) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);//这里可能根据需要改成application/json方式 
            ObjectMapper om = new ObjectMapper();
            String queryString = om.writeValueAsString(queryParam);
            HttpEntity<String> entity = new HttpEntity<>(queryString,headers);
            ResponseEntity<String> res = restTemplate.postForEntity(queryUrl,entity,String.class);
            return res.getBody();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

 hutool发送的post请求,好像一定要用它的jsonobject组装参数,不然用不了,不知道什么原因

cn.hutool.json.JSONObject queryParam = JSONUtil.createObj();
queryParam.put("data",keys);

//////////////
public String doPost(String queryUrl, cn.hutool.json.JSONObject queryParam) {
        try {

            String result = HttpRequest.post(queryUrl)
                    .header("Content-Type","application/json")
                    .body(queryParam.toString())
                    .execute().body();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
}

 

posted on 2021-04-14 16:24  greatbing  阅读(2229)  评论(0编辑  收藏  举报