package com.nikooh.manage.util;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Objects;
import java.util.Optional;
public final class RestClient {
private static final Logger LOGGER = LoggerFactory.getLogger(RestClient.class);
private static RestTemplate restTemplate;
private HttpEntity httpEntity;
private HttpHeaders httpHeaders;
private String contentType;
private HashMap<String, Object> params;
private RestClient() {
}
static {
HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory
= new HttpComponentsClientHttpRequestFactory();
httpComponentsClientHttpRequestFactory.setConnectTimeout(10000);
httpComponentsClientHttpRequestFactory.setReadTimeout(30000);
restTemplate = new RestTemplate(httpComponentsClientHttpRequestFactory);
}
public static RestClient build() {
return new RestClient();
}
public RestClient addHeader(String headerName, String headerValue) {
this.httpHeaders = Optional.ofNullable(this.httpHeaders).orElse(new HttpHeaders());
this.httpHeaders.add(headerName, headerValue);
return this;
}
public RestClient addParams(String paramName, Object paramValue) {
this.params = Optional.ofNullable(this.params).orElse(new HashMap<>());
this.params.put(paramName, paramValue);
return this;
}
public RestClient addContentType(String contentType) {
if (StringUtils.isBlank(contentType)) {
LOGGER.error("RestClient.build---------->content-Type can not be empty!");
throw new RuntimeException("content-Type can not be empty!");
}
this.contentType = contentType;
this.httpHeaders = Optional.ofNullable(this.httpHeaders).orElse(new HttpHeaders());
this.httpHeaders.setContentType(MediaType.parseMediaType(contentType));
return this;
}
private void create() {
if (Objects.isNull(this.params)) {
LOGGER.error("RestClient.build---------->body must be not empty!");
throw new RuntimeException("body must be not empty!");
}
if (Objects.isNull(contentType) || ContentType.APPLICATION_JSON.getMimeType().equals(contentType)) {
this.addContentType(ContentType.APPLICATION_JSON.getMimeType());
JSONObject jsonObject = new JSONObject();
for (String s : params.keySet()) {
try {
jsonObject.put(s, params.get(s));
} catch (JSONException e) {
LOGGER.error("RestClient.build---------->JSONException:[{}]", e.getMessage());
throw new JSONException("params set error!");
}
}
String body = jsonObject.toString();
this.httpEntity = new HttpEntity<>(body, this.httpHeaders);
} else if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType)) {
MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
for (String s : params.keySet()) {
formData.add(s, params.get(s));
}
this.httpEntity = new HttpEntity<>(formData, this.httpHeaders);
} else {
LOGGER.error("RestClient.build---------->content-Type not supported!");
throw new RuntimeException("content-Type not supported!");
}
}
public <T> T get(String url, Class<T> clazz) {
ResponseEntity<T> entity = restTemplate.getForEntity(url, clazz, this.params);
if (HttpStatus.OK.equals(entity.getStatusCode())) {
return entity.getBody();
} else {
LOGGER.error("RestClient.get---------->get error! status:[{}]", entity.getStatusCode().toString());
throw new RuntimeException(entity.getStatusCode().toString());
}
}
public <T> T post(String url, Class<T> clazz) {
this.create();
ResponseEntity<T> entity = restTemplate.postForEntity(url, this.httpEntity, clazz);
if (HttpStatus.OK.equals(entity.getStatusCode())) {
return entity.getBody();
} else {
LOGGER.error("RestClient.post---------->post error! status:[{}]", entity.getStatusCode().toString());
throw new RuntimeException(entity.getStatusCode().toString());
}
}
public <T> T exchange(String url, Class<T> clazz, HttpMethod method) {
this.create();
ResponseEntity<T> entity = restTemplate.exchange(url, method, this.httpEntity, clazz);
if (HttpStatus.OK.equals(entity.getStatusCode())) {
return entity.getBody();
} else {
log.error("RestClient.exchange---------->exchange error! status:[{}]", entity.getStatusCode().toString());
throw new RuntimeException(entity.getStatusCode().toString());
}
}
}
使用方法
JSONObject result = RestClient.build()
.addContentType("application/json")
.addHeader("Authorization","Bearer bbc56d43-ec30-4ab5-af8c-516a5e739")
.addHeader("scope","web")
.addParams("id",1)
.addParams("name","zhangsan")
.post("https://www.baidu.com", JSONObject.class);