第一步:新建marven项目,并配置marven
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sunjian</groupId>
<artifactId>httpclientsutil</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
</dependencies>
</project>
第二步:编写HttpClientUtils,并进行代码测试
httpclient的get请求
package com.sunjian;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientUtils {
public static void main(String[] args) throws ClientProtocolException, IOException {
get("http://www.jianshu.com/");
}
static public void get(String url) throws ClientProtocolException, IOException{
//创建一个默认连接
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
//获取状态吗,判断状态
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode==200){
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity,"UTF-8");
System.out.println("result:"+result);
}
}
}
httpclient的post请求
static public void post(String url) throws ClientProtocolException, IOException{
//创建一个默认连接
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("token","644064");
List<NameValuePair> listNameValuePair = new ArrayList<NameValuePair>();
listNameValuePair.add(new BasicNameValuePair("userName", "123456"));
listNameValuePair.add(new BasicNameValuePair("pwd", "646525"));
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(listNameValuePair,"UTF-8");
httpPost.setEntity(urlEncodedFormEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
//获取状态码
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == 200){
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity,"UTF-8");
System.out.println("result:"+result);
}
}
测试效果:
关注我的公众号,都是满满的干货!