package com.monkeylessey.utils;
|
|
import lombok.RequiredArgsConstructor;
|
import org.springframework.http.HttpEntity;
|
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpMethod;
|
import org.springframework.http.ResponseEntity;
|
import org.springframework.lang.Nullable;
|
import org.springframework.stereotype.Component;
|
import org.springframework.util.MultiValueMap;
|
import org.springframework.web.client.RestTemplate;
|
|
/**
|
* @author xp
|
* @date 2022/11/16
|
*/
|
@Component
|
@RequiredArgsConstructor
|
public class HttpUtil {
|
|
private final RestTemplate httpClient;
|
|
/**
|
* post
|
*
|
* @param url 请求连接(ps: post请求如果要传url参数,请先拼接好再传入url)
|
* @param data 请求体数据
|
* @param header 请求头(有token就放里面)
|
* @return
|
*/
|
public Object post(String url, @Nullable Object data, @Nullable MultiValueMap header) {
|
ResponseEntity<Object> response = httpClient.exchange(
|
url,
|
HttpMethod.POST,
|
getHttpEntity(data, header),
|
Object.class
|
);
|
return response.getBody();
|
}
|
|
/**
|
* @param url 请求连接 (ps: post请求如果要传url参数,请先拼接好再传入url)
|
* @param data 请求体数据
|
* @param token
|
* @return
|
*/
|
public Object post(String url, String token, @Nullable Object data) {
|
ResponseEntity<Object> response = httpClient.exchange(
|
url,
|
HttpMethod.POST,
|
getHttpEntity(data, token),
|
Object.class
|
);
|
return response.getBody();
|
}
|
|
/**
|
* get
|
*
|
* @param url RestTemplate 如果有url参数,必须要在url中使用占位符,如:https://www.easyblog.vip?name={name} 传参:String name = xp,才能拼上这个参数
|
* @param token
|
* @param params
|
* @return
|
*/
|
public Object get(String url, String token, @Nullable Object... params) {
|
ResponseEntity<Object> response = httpClient.exchange(
|
url,
|
HttpMethod.GET,
|
getHttpEntity(null, token),
|
Object.class,
|
params
|
);
|
return response.getBody();
|
}
|
|
/**
|
* get
|
*
|
* @param url 请求连接 RestTemplate 如果有url参数,必须要在url中使用占位符,如:https://www.easyblog.vip?name={name} 传参:String name = xp,才能拼上这个参数
|
* @param header 请求头(有token就放里面)
|
* @param params
|
* @return
|
*/
|
public Object get(String url, @Nullable MultiValueMap header, @Nullable Object... params) {
|
ResponseEntity<Object> response = httpClient.exchange(
|
url,
|
HttpMethod.GET,
|
getHttpEntity(null, header),
|
Object.class,
|
params
|
);
|
return response.getBody();
|
}
|
|
|
/**
|
* 构建带请求头和请求体的httpEntity
|
*
|
* @param data
|
* @param token
|
* @return
|
*/
|
protected HttpEntity getHttpEntity(Object data, String token) {
|
MultiValueMap<String, String> header = new HttpHeaders();
|
header.add("Authorization", token);
|
HttpEntity httpEntity = new HttpEntity(data, header);
|
return httpEntity;
|
}
|
|
/**
|
* 直接传入header
|
*
|
* @param data
|
* @param header
|
* @return
|
*/
|
protected HttpEntity getHttpEntity(Object data, MultiValueMap header) {
|
HttpEntity httpEntity = new HttpEntity(data, header);
|
return httpEntity;
|
}
|
|
}
|