java使用HttpClient发送Http请求post方式
1、引入依赖
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
2、发送请求
public static void main(String[] args) throws IOException {
HttpClient httpClient = new HttpClient();
//设置连接超时时间
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(2 * 60 * 1000);
//创建post请求实例对象
PostMethod postMethod = new PostMethod("http://localhost:8001/admin/api/categoryProduct");
//设置post请求超时时间
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60 * 1000);
//设置编码
postMethod.getParams().setHttpElementCharset("usf-8");
postMethod.getParams().setContentCharset("usf-8");
postMethod.getParams().setUriCharset("usf-8");
//设置请求头
postMethod.addRequestHeader("Content-Type","application/json");
//设置json参数
JSONObject jsonObject = new JSONObject();
jsonObject.put("categoryId",1);
postMethod.setRequestBody(jsonObject.toJSONString());
//发送请求
httpClient.executeMethod(postMethod);
String result = postMethod.getResponseBodyAsString();
//释放连接
postMethod.releaseConnection();
System.out.println(result);