使用 RestTemplate 发送 post请求(json参数)

使用json作为参数版本

import net.sf.json.JSONObject;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.util.Iterator;

//调用post请求
    public static JSONObject callPostAPI(String url, JSONObject header, JSONObject body) {

            RestTemplate client = new RestTemplate();

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

            //设置其他头信息
            Iterator iterator = header.keys();
            while(iterator.hasNext()){
                String key = (String) iterator.next();
                String value = header.getString(key);
                headers.add(key, value);
            }

            HttpEntity formEntity = new HttpEntity(body.toString(), headers);
            JSONObject json = client.postForEntity(url, formEntity, JSONObject.class).getBody();
            System.out.println("json:"+json.toString());
            return json;
    }

你可能感兴趣的:(课程学习,java,http)