import com.zzb.business.customerInfo.config.ReportConfig;
import com.zzb.business.customerInfo.config.connection.PengYuanConfig;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.IOException;
import java.util.Map;
/**
* @author edison_kwok
*/
public class RestTemplateUtils {
/**
* 可以设置请求头参数和请求体参数的post方法
*
* @param url
* @param headers
* @param params
* @param restTemplate
* @return
*/
public static String postConnect(String url, Map<String, String> headers, Map<String, String> params, RestTemplate restTemplate) {
//header信息,包括了http basic认证信息
MultiValueMap<String, String> headersMap = new LinkedMultiValueMap<>();
for (String key : headers.keySet()) {
headersMap.add(key, headers.get(key));
}
//body请求体部分
MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>();
for (String key : params.keySet()) {
bodyMap.add(key, params.get(key));
}
//merge成为一个HttpEntity
HttpEntity<MultiValueMap<String, String>> multiValueMapHttpEntity = new HttpEntity<>(bodyMap, headersMap);
//当响应的值为400或401时候也要正常响应,不要抛出异常
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
if (response.getRawStatusCode() != 400 || response.getRawStatusCode() != 401) {
super.handleError(response);
}
}
});
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, multiValueMapHttpEntity, String.class);
return responseEntity.getBody();
}
/**
* 上传文件到文件系统
*
* @param file
* @return
*/
public static String upload(File file, RestTemplate restTemplate, String uploadUrl) {
if (!file.exists()) {
return null;
}
//将文件传入文件管理系统
FileSystemResource resource = new FileSystemResource(file);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file", resource);
ResponseEntity<String> pathEntity = restTemplate.postForEntity(uploadUrl, param, String.class);
//删除本地文件
file.delete();
//返回文件路径 例如:risk/file/customerReport/20190621/19062113582560509589.pdf
try {
return JsonUtils.parse(pathEntity.getBody(), new Object[0]);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
转载于:https://my.oschina.net/edisonOnCall/blog/3080224