/**
* post请求
* @param url 请求地址
* @param b 设置到body中的参数字节数组
* @param map 参数map
* @return 返回接口字符串
* @throws Exception
*/
public static String httpPost(String url, byte[] b, Map<String, String> map) throws Exception {
// 返回body
String body = "";
// 1、创建一个htt客户端
HttpClient httpClient = new DefaultHttpClient();
// 2、创建一个HttpPost请求
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setHeader("charset", "UTF-8");
post.setEntity(new StringEntity("image=" + Base64AndUrlEncodeBytes(b)));
// 5、设置header信息
post.setHeader("X-Appid", APPID);
post.setHeader("X-CurTime", getUTCTimeStr());
post.setHeader("X-Param", Base64String(param));
post.setHeader("X-CheckSum", MD5String(APIKey + getUTCTimeStr() + Base64String(param)));
// post.setHeader("Connection", "close");
// 设置参数
if (map != null) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
post.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
}
// 7、执行post请求操作,并拿到结果
HttpResponse httpResponse = httpClient.execute(post);
// 获取结果实体
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
// 按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, HTTP.UTF_8);
}
// EntityUtils.consume(entity);
httpClient.getConnectionManager().shutdown();
System.out.println(body.length());
return body;
}
maven依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.1.2</version>
</dependency>
该post请求方法中有其他的几个编码的方法,对参数编码是我调用的接口规定必须如此,因此对于参数的编码格式,还需要根据实际的api要求来进行设置。
————————————————————————————————————————
最后,庆祝自己大难不死。这个吊毛大货车,差点把我卷进车轮子下面。告诫广大网友,在马路上,一定要小心,远离大货车。