HttpClient发送Post请求(一)
2017-06-29 11:42
197 查看
pom
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency>
code
package com.xxxxxx.xxxxx; import java.io.IOException; import java.nio.charset.Charset; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * @author wushucheng * @version 创建时间:2017年6月28日 下午5:20:23 * @TODO 类说明 */ public class HttpUtil { public static String post(String url, String body){ String result = null; CloseableHttpClient client = null; CloseableHttpResponse response = null; try { client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); StringEntity stringEntity = new StringEntity(body, Charset.forName("UTF-8")); httpPost.setEntity(stringEntity); response = client.execute(httpPost); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ if(response != null){ try { response.close(); } catch (IOException e) { e.printStackTrace(); } } if(client != null){ try { client.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } }
attention
以上代码可以发送 http/https post 请求调用微信API的时候,若body存在中文,一定要进行 UTF-8 转码,否则会报错
相关文章推荐
- HttpClient模拟get,post请求并发送请求参数(json等)
- java 利用httpclient 3.1 和 httpclient4.1.2发送post请求
- httpurlconnection 和 httpclient 发送get、post请求
- 使用HttpClient发送GET和POST请求
- 使用HttpClient发送GET、POST请求
- HttpClient模拟get,post请求并发送请求参数(json等)
- 使用HttpClient 发送 GET、POST、PUT、Delete请求及文件上传
- 使用httpclient发送get/post请求
- 使用HttpClient来异步发送POST请求并解析GZIP回应
- HttpClient模拟get,post请求并发送请求参数(json等)
- Java 基于HttpClient和fluent-hc发送POST请求
- 使用HttpClient发送HttpPost请求包含上传本地图片和远程图片的传输实现
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- httpClient使用,1 发送post请求 2 发送get请求取得接口中的数据
- java apache commons HttpClient发送get和post请求的学习整理
- java使用httpclient发送post请求示例
- httpclient就是个能发送http连接的工具包,包括能发送post请求和get请求
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- 利用HTTPClient模块中HttpGet和HttpPost 发送接口请求
- HttpClient模拟get,post请求并发送请求参数(json等)