如何快速写一个 Http Client

项目中快速完成一个 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 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():"";
    }
}

你可能感兴趣的:(Java,web,http,client)