HttpClient之post请求

直接看代码:

package cn.itcast.crawler.test;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpPostTest {
public static void main(String[] args) {
//1.创建HttpClient对象
CloseableHttpClient httpClient= HttpClients.createDefault();
//2.创建HttpPost对象,设置URL地址
HttpPost httpPost=new HttpPost("http://www.itcast.cn");;
//使用httpClient发起响应获取repsonse
CloseableHttpResponse response=null;
try {
response=httpClient.execute(httpPost);
//4.解析响应,获取数据
//判断状态码是否是200
if(response.getStatusLine().getStatusCode()==200){
HttpEntity httpEntity=response.getEntity();
String content=EntityUtils.toString(httpEntity,"utf8");
System.out.println(content.length());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
}
执行结果:

HttpClient之post请求

其实post请求和get请求在代码编写方面是非常相似的,只是一个是创建HttpPost对象,一个是创建HttpGet对象

上一篇:springBoot框架下配置HttpClient远程服务调用


下一篇:httpPost接口服务器接收数据和传输数据代码范例