引入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
导入jar包
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
发起HTTP请求
get方法
String url = "url";
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpGet);
//HttpStatus.SC_OK = 200
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
JSONObject obj = JSONObject.parseObject(res);
System.out.println(obj);
}
} catch (IOException e) {
e.printStackTrace();
}
post方法
JSONObjcet result = new JSONObject();
// 创建HttpPost对象,设置URL地址
HttpPost httpPost=new HttpPost(URL);
// 封装参数
JSONObject param = new JSONObject();
param.put("name","tom");
//装填参数
StringEntity entity = new StringEntity(param.toString(), "utf-8");
entity .setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
//设置参数到请求对象中
httpPost.setEntity(entity);
//设置报头
httpPost.setHeader("Content-type", "application/json");
try{
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = httpClient.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
String res = EntityUtils.toString(entity, "UTF-8");
result= JSONObject.parseObject(res);
}
//释放链接
response.close();
}catch (IOException e) {
e.printStackTrace();
}
return result;