com.zyy.common.util.HttpUtil Maven / Gradle / Ivy
package com.zyy.common.util;
import com.zyy.common.http.Http;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import javax.annotation.PostConstruct;
import java.util.Map;
@Slf4j
public class HttpUtil {
private static RestTemplate template;
private final RestTemplate restTemplate;
public HttpUtil(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@PostConstruct
public void init() {
template = restTemplate;
}
public static String sendTo(Http http) {
String url = http.getUrl();
HttpMethod method = HttpMethod.valueOf(http.getMethod().toUpperCase());
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map map = http.getHeader();
if (map != null && map.size() > 0) {
for (String key : map.keySet()) {
headers.set(key, map.get(key));
}
}
// 设置访问参数
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParams(http.getParams());
// 设置访问的Entity
HttpEntity entity = new HttpEntity<>(http.getBody(), headers);
ResponseEntity exchange = template.exchange(builder.toUriString(), method, entity, String.class);
return exchange.getBody();
}
}