依赖
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
引入包
import com.alibaba.fastjson2.JSON;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
POST 有参数
public A findXxx(String code) {
A a= null;
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
log.info("HttpUrl:{}", url);
httpPost.setHeader("xxx", "xxx");
Map<String, Object> params = new HashMap<>();
params.put("xxx", "xxx");
httpPost.setEntity(new StringEntity(JSON.toJSONString(params)));
try (CloseableHttpResponse response = client.execute(httpPost)) {
if (response.getCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
String jsonString = EntityUtils.toString(httpEntity);
log.info("findXxxResponse:{}", jsonString);
if (jsonString.contains("errorCode")) {
log.error("findXxxFail:{}", jsonString);
} else {
a = JSON.parseObject(jsonString, A.class);
}
} else {
log.error("findXxxFail:{}", response);
}
} catch (Exception e) {
log.error(ResultCode.HTTP_FAIL.message(), e);
} finally {
httpPost.reset();
}
return a;
}
GET 无参数
public A findXxx(String code) {
A a= null;
CloseableHttpClient client = HttpClients.createDefault();
String url = xxxUrl + "?xxx=xxx";
HttpGet httpGet = new HttpGet(url);
log.info("HttpUrl:{}", url);
httpGet.setHeader("xxx", "xxx");
try (CloseableHttpResponse response = client.execute(httpGet)) {
if (response.getCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
String jsonString = EntityUtils.toString(httpEntity);
log.info("findXxxResponse:{}", jsonString);
if (jsonString.contains("errorCode")) {
log.error("findXxxFail:{}", jsonString);
} else {
a = JSON.parseObject(jsonString, A.class);
}
} else {
log.error("findXxxFail:{}", response);
}
} catch (Exception e) {
log.error(ResultCode.HTTP_FAIL.message(), e);
} finally {
httpGet.reset();
}
return a;
}