springboot2.0 webClient api 调用

import java.util.Map;

import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClient.RequestBodySpec;
import reactor.core.publisher.Mono;

/**
* @Description:
* @author lukew
* @email 13507615840@163.com
* @date 2018年3月31日 上午9:25:47
*/
public class WebClientUtil {

private static final MediaType MEDIATYPE = MediaType.APPLICATION_JSON_UTF8;

/**
 * 
 * @param paramter
 *            请求参数
 * @param url
 *            请求路径
 * @param resultType
 *            返回结果类型
 * @return
 */
public static <V> V post(Object paramter, String url, Class<V> resultType) {

    return post(uri(url, HttpMethod.POST), paramter, resultType);
}

/**
 * 
 * @param paramter
 *            请求参数
 * @param url
 *            请求路径
 * @param header
 *            请求头
 * @param resultType
 *            返回结果类型
 * @return
 */
public static <V> V post(Object paramter, String url, Map<String, String> header, Class<V> resultType) {

    RequestBodySpec uri = uri(url, HttpMethod.POST);
    addHeader(header, uri);
    return post(uri, paramter, resultType);
}

private static <V> V post(RequestBodySpec uri, Object paramter, Class<V> resultType) {

    return uri.contentType(MEDIATYPE).body(Mono.just(paramter), Object.class).retrieve().bodyToMono(resultType)
            .block();
}

/**
 * 
 * @param url
 *            请求路径
 * @param resultType
 *            返回结果类型
 * @return
 */
public static <V> V get(String url, Class<V> resultType) {

    return uri(url, HttpMethod.GET).retrieve().bodyToMono(resultType).block();
}

/**
 * 
 * @param url
 *            请求路径
 * @param header
 *            请求头
 * @param resultType
 *            返回结果类型
 * @return
 */
public static <V> V get(String url, Map<String, String> header, Class<V> resultType) {

    RequestBodySpec uri = uri(url, HttpMethod.GET);
    addHeader(header, uri);
    return uri.retrieve().bodyToMono(resultType).block();
}

private static RequestBodySpec uri(String url, HttpMethod method) {

    return WebClient.create().method(method).uri(url);
}

private static void addHeader(Map<String, String> header, RequestBodySpec uri) {

    if (!CollectionUtils.isEmpty(header)) {
        header.forEach((name, value) -> uri.cookie(name, value));
    }
}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值