HttpClient如何发送post请求调用接口呢?
下文笔者讲述HttpClient请求post接口时,在方法体和body中设置参数的方法分享,如下所示
实现思路: 1.使用maven引入相应的jar包 2.使用setEntity即可将参数信息放入例:
引入jar包
<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请求 * @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; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。