如何快速写一个 Http Client
程序员文章站
2024-03-23 10:14:28
...
项目中快速完成一个 Http Client 可以参考以下
Okhttp 使用
https://square.github.io/okhttp/
Hutool Http客户端-HttpRequest 使用
https://www.hutool.cn/docs/#/http/Http%E8%AF%B7%E6%B1%82-HttpRequest
@Slf4j
public class HttpRequset {
private static final String TOKEN_NAME="tokenName";
private static final String CONTENT_TYPE="application/vnd.api+json";
public static String getRequset(String host,String uri,Object params){
if(Objects.nonNull(params)) {
Map<String, Object> mapParams= BeanUtil.beanToMap(params, false, true);
String paramsStr = "?".concat(HttpUtil.toParams(mapParams));
uri=uri.concat(paramsStr);
}
String url= StrUtil.format(Aps.REST_API,host,uri);
log.info("url:{}",url);
HttpResponse response = HttpUtil.createGet(url)
.header(TOKEN_NAME, Aps.token)
.contentType(CONTENT_TYPE)
.header(Header.ACCEPT.toString(), ContentType.JSON.toString())
.execute();
log.info("Get请求返回:{}",response.getStatus());
return response.isOk()?response.body():"";
}
public static String postRequset(String host,String uri,String json){
String url= StrUtil.format(Aps.REST_API,host,uri);
log.info("url:{},参数:{}",url,json);
HttpResponse response = HttpUtil.createPost(url)
.header(TOKEN_NAME, Aps.token)
.contentType(CONTENT_TYPE)
.header(Header.ACCEPT.toString(), ContentType.JSON.toString())
.body(json)
.execute();
log.info("Post请求返回:{}",response.getStatus());
return response.isOk()?response.body():"";
}
}
上一篇: 内存对齐(结构体)