1.发起POST请求的前提
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity httpEntity = new MultipartEntity();
client请求的执行体
httpPost是请求中的参数的主要负载体
httpEntity是具体承载参数的地方
2.设置header
httpPost.setHeader(String name, String value)
3.设置请求值
post的请求参数是通过
httpPost.setEntity(HttpEntity entity)
HttpEntity这个借口有一堆实现类,这些类都可以作为值得载体,可以根据不同的请求方式选取不同的载体

image.png
可以看到有这些个实现类,这里举俩个常用的
1)模拟表单的post请求
这种请求需要用到上边我们实例化的MultipartEntity类,顾名思义这是意思多个参数,它的主要方法是
httpEntity.addPart(String name, ContentBody contentBody)
其中ContentBody是个接口,它的实现类也就是对应表单提交的文字,文件等

image.png
常用的
StringBody就是提交文字了ByteArrayBody、FileBody、InputStreamBody分别对应文件的几种格式 可以按需选择
2)传递JSON格式内容
JSON字符串的请求体内容本质就是字符串,但是一般要求在头上加上
httpPost.setHeader("Content-Type", "application/json");
主体内容的传递是通过StringEntity作为载体
new StringEntity(jsonObject.toJSONString(), "utf-8")
当参数组装好后,需要调用httpPost.setEntity(HttpEntity entity)将数据加入,··
4.发起请求
client.execute(httpPost)
5.接受解析返回值
// 对返回结果进行处理 获取返回的汇川数据储存信息
HttpEntity responseEntity = response.getEntity();
StringBuilder builder = new StringBuilder();
if (responseEntity != null) {
InputStream is = responseEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is,UTF_8));
String tempStr;
while ((tempStr = br.readLine()) != null) {
builder.append(tempStr);
}
br.close();
}
注意一般塞入参数的时候可以设置编码的地方一定要设置编码,防止因为环境产生问题