1.方式一
public static void request(String proposalId) {
//请求的body信息
String requestBody = "{proposalId:" + proposalId + "}";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(jsseuri);
//添加header
httpPost.addHeader("X-Easymi-AppCode", "AppCode");
httpPost.addHeader("X-Easymi-UserName", "UserName");
//添加body
ByteArrayEntity entity = null;
try {
entity = new ByteArrayEntity(requestBody.getBytes("UTF-8"));
entity.setContentType("application/json");
} catch (UnsupportedEncodingException e) {
logger.error("向服务器承保接口发起http请求,封装请求body时出现异常", e);
throw new RuntimeException("向服务器承保接口发起http请求,封装请求body时出现异常", e);
}
httpPost.setEntity(entity);
//执行post请求
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
logger.error("提交给服务器的请求,不符合HTTP协议", e);
throw new RuntimeException("提交给服务器的请求,不符合HTTP协议", e);
} catch (IOException e) {
logger.error("向服务器承保接口发起http请求,执行post请求异常", e);
throw new RuntimeException("向服务器承保接口发起http请求,执行post请求异常", e);
}
logger.info("状态码:" + response.getStatusLine());
}

获取:流方法获取

public static String getHttpBody(HttpServletRequest request) {
String data = "";

    try {
        InputStream in = request.getInputStream();
        InputStreamReader isr = new InputStreamReader(in, "utf-8");
        BufferedReader br = new BufferedReader(isr);

        for(String temp = ""; (temp = br.readLine()) != null; data = data + temp) {
            ;
        }
    } catch (IOException var7) {
        var7.printStackTrace();
    }

    if (data.indexOf("BODY_DATA") != -1) {
        try {
            data = URLDecoder.decode(data.substring("BODY_DATA=".length()), "utf-8");
        } catch (UnsupportedEncodingException var6) {
            var6.printStackTrace();
        }
    }

    return data;
}

2、字符串方法获取
@RequestMapping(value = "/string/test", method = RequestMethod.POST)
public void getHttpBodyByStr(HttpServletRequest request) throws Exception {
// 定义一个字符输入流
BufferedReader br = null;
// 定义一个可变字符串 这里不考虑线程安全问题 所以用StringBuilder
StringBuilder sb = new StringBuilder("");
br = request.getReader();
String str;
while ((str = br.readLine()) != null){
sb.append(str);
}
br.close();
String resStr = sb.toString();
System.out.println(resStr);

}

方式二:
public static String httpPostJson(String url, String json) {
if (url == null || "".equals(url)) {
log.error("url为null!");
return "";
}
MediaType JSON = MediaType.parse(HTTP_JSON);
RequestBody body = RequestBody.create(JSON, json);
Request.Builder requestBuilder = new Request.Builder().url(url);
Request request = requestBuilder.post(body).build();
try {
Response response = okHttpClient.newCall(request).execute();
int code = 200;
if (code == response.code()) {
log.info("http Post 请求成功; [url={}]", url);
return response.body().string();
} else {
log.warn("Http POST 请求失败; [ errorCode = {}, url={}]", response.code(), url);
}
} catch (Exception e) {
throw new RuntimeException("同步http请求失败,url:" + url, e);
}
return null;
}