package jnpf.util.wxutil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import jnpf.util.*;
import jnpf.util.context.SpringContext;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* @author JNPF开发平台组
* @version V3.1.0
* @copyright 引迈信息技术有限公司
* @date 2021/3/16 8:49
*/
@Slf4j
public class HttpUtil {
private HttpUtil() {
throw new IllegalAccessError("工具类不能实例化");
}
private static PoolingHttpClientConnectionManager connectionManager = null;
private static RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(3000)
.build();
static {
SSLContext sslcontext = SSLContexts.createSystemDefault();
Registry<ConnectionSocketFactory> socketFactoryRegistry =
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext)).build();
connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(1000);
// 每个路由最大的请求数量
connectionManager.setDefaultMaxPerRoute(200);
}
public static CloseableHttpClient getHttpClient() {
return getHttpClientBuilder().build();
}
public static CloseableHttpClient getHttpClient(SSLContext sslContext) {
return getHttpClientBuilder(sslContext).build();
}
public static HttpClientBuilder getHttpClientBuilder() {
return HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig);
}
public static HttpClientBuilder getHttpClientBuilder(SSLContext sslContext) {
if (sslContext != null) {
return getHttpClientBuilder().setSSLContext(sslContext);
} else {
return getHttpClientBuilder();
}
}
/**
* post 请求
*
* @param httpUrl 请求地址
* @param sslContext ssl证书信息
* @return
*/
public static String sendHttpPost(String httpUrl, SSLContext sslContext) {
// 创建httpPost
HttpPost httpPost = new HttpPost(httpUrl);
return sendHttpPost(httpPost, sslContext);
}
/**
* 发送 post请求
*
* @param httpUrl 地址
*/
public static String sendHttpPost(String httpUrl) {
// 创建httpPost
HttpPost httpPost = new HttpPost(httpUrl);
return sendHttpPost(httpPost, null);
}
/**
* 发送 post请求
*
* @param httpUrl 地址
* @param params 参数(格式:key1=value1&key2=value2)
*/
public static String sendHttpPost(String httpUrl, String params) {
return sendHttpPost(httpUrl, params, null);
}
/**
* 发送 post请求
*
* @param httpUrl 地址
* @param params 参数(格式:key1=value1&key2=value2)
* @param sslContext ssl证书信息
*/
public static String sendHttpPost(String httpUrl, String params, SSLContext sslContext) {
// 创建httpPost
HttpPost httpPost = new HttpPost(httpUrl);
try {
// 设置参数
StringEntity stringEntity = new StringEntity(params, Constants.UTF8);
stringEntity.setContentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
httpPost.setEntity(stringEntity);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return sendHttpPost(httpPost, sslContext);
}
/**
* 发送 post请求
*
* @param httpUrl 地址
* @param maps 参数
*/
public static String sendHttpPost(String httpUrl, Map<String, String> maps) {
return sendHttpPost(httpUrl, maps, null);
}
/**
* 发送 post请求
*
* @param httpUrl 地址
* @param maps 参数
* @param sslContext ssl证书信息
*/
public static String sendHttpPost(String httpUrl, Map<String, String> maps, SSLContext sslContext) {
HttpPost httpPost = wrapHttpPost(httpUrl, maps);
return sendHttpPost(httpPost, null);
}
/**
* 封装获取HttpPost方法
*
* @param httpUrl
* @param maps
* @return
*/
public static HttpPost wrapHttpPost(String httpUrl, Map<String, String> maps) {
// 创建httpPost
HttpPost httpPost = new HttpPost(httpUrl);
// 创建参数队列
List<NameValuePair> nameValuePairs = new ArrayList<>();
for (Map.Entry<String, String> m : maps.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(m.getKey(), m.getValue()));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, Constants.UTF8));
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return httpPost;
}
/**
* 发送 post请求(带文件)
*
* @param httpUrl 地址
* @param file 附件,名称和File对应
*/
public static String sendHttpPost(String httpUrl, File file) {
return sendHttpPost(httpUrl, ImmutableMap.of("media", file), null, null);
}
/**
* 发送 post请求(带文件)
*
* @param httpUrl 地址
* @param file 附件,名称和File对应
* @param maps 参数
*/
public static String sendHttpPost(String httpUrl, File file, Map<String, String> maps) {
return sendHttpPost(httpUrl, ImmutableMap.of("media", file), maps, null);
}
/**
* 发送 post请求(带文件),默认 files 名称数组.
*
* @param httpUrl 地址
* @param fileLists 附件
* @param maps 参数
*/
public static String sendHttpPost(String httpUrl, List<File> fileLists, Map<String, String> maps) {
return sendHttpPost(httpUrl, fileLists, maps, null);
}
/**
* 发送 post请求(带文件)
*
* @param httpUrl 地址
* @param fileMap 附件,名称和File对应
* @param maps 参数
*/
public static String sendHttpPost(String httpUrl, Map<String, File> fileMap, Map<String, String> maps) {
return sendHttpPost(httpUrl, fileMap, maps, null);
}
/**
* 发送 post请求(带文件),默认 files 名称数组.
*
* @param httpUrl 地址
* @param fileLists 附件
* @param maps 参数
* @param sslContext ssl证书信息
*/
public static String sendHttpPost(String httpUrl, List<File> fileLists, Map<String, String> maps,
SSLContext sslContext) {
Map<String, File> fileMap = new HashMap<>(16);
if (fileLists == null || fileLists.isEmpty()) {
for (File file : fileLists) {
fileMap.put("media", file);
}
}
return sendHttpPost(httpUrl, fileMap, maps, sslContext);
}
/**
* 发送 post请求(带文件)
*
* @param httpUrl 地址
* @param fileMap 附件,名称和File对应
* @param maps 参数
* @param sslContext ssl证书信息
*/
public static String sendHttpPost(String httpUrl, Map<String, File> fileMap, Map<String, String> maps,
SSLContext sslContext) {
// 创建httpPost
HttpPost httpPost = new HttpPost(httpUrl);
MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
if (null != maps) {
for (Map.Entry<String, String> m : maps.entrySet()) {
meBuilder.addPart(m.getKey(), new StringBody(m.getValue(), ContentType.TEXT_PLAIN));
}
}
if (null != fileMap) {
for (Map.Entry<String, File> m : fileMap.entrySet()) {
FileBody fileBody = new FileBody(m.getValue());
meBuilder.addPart(m.getKey(), fileBody);
}
}
HttpEntity reqEntity = meBuilder.build();
httpPost.setEntity(reqEntity);
return sendHttpPost(httpPost, sslContext);
}
/**
* 发送Post请求
*
* @param httpPost
* @return
*/
public static String sendHttpPost(HttpPost httpPost) {
return sendHttpPost(httpPost, null);
}
/**
* 发送Post请求
*
* @param httpPost
* @param sslConext ssl证书信息
* @return
*/
public static String sendHttpPost(HttpPost httpPost, SSLContext sslConext) {
CloseableHttpClient httpClient = getHttpClient(sslConext);
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 执行请求
response = httpClient.execute(httpPost);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, Constants.UTF8);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
// 关闭连接,释放资源
if (entity != null) {
// 会自动释放连接
EntityUtils.consumeQuietly(entity);
}
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
return responseContent;
}
/**
* 发送 get请求
*
* @param httpUrl
*/
public static String sendHttpGet(String httpUrl) {
return sendHttpGet(httpUrl, null);
}
/**
* 发送 get请求
*
* @param httpUrl
* @param sslConext ssl证书信息
*/
public static String sendHttpGet(String httpUrl, SSLContext sslConext) {
// 创建get请求
HttpGet httpGet = new HttpGet(httpUrl);
return sendHttpGet(httpGet, sslConext);
}
/**
* 发送Get请求
*
* @param httpGet
* @return
*/
public static String sendHttpGet(HttpGet httpGet) {
return sendHttpGet(httpGet, null);
}
/**
* 发送Get请求
*
* @param httpGet
* @param sslConext ssl证书信息
* @return
*/
public static String sendHttpGet(HttpGet httpGet, SSLContext sslConext) {
CloseableHttpClient httpClient = getHttpClient(sslConext);
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 执行请求
response = httpClient.execute(httpGet);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, Constants.UTF8);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
// 关闭连接,释放资源
if (entity != null) {
// 会自动释放连接
EntityUtils.consumeQuietly(entity);
}
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
return responseContent;
}
/**
* 发送 get请求
*
* @param httpUrl 请求路径
* @param headers 请求头参数
* @return
*/
public static String sendHttpHeaderGet(String httpUrl, Map<String, String> headers) {
// 创建get请求
HttpGet httpGet = new HttpGet(httpUrl);
for (Map.Entry<String, String> entry : headers.entrySet()) {
String key = entry.getKey().toString();
String value = entry.getValue().toString();
httpGet.setHeader(key, value);
}
return sendHttpGet(httpGet, null);
}
/**
* Get 下载文件
*
* @param httpUrl
* @param file
* @return
*/
public static File sendHttpGetFile(String httpUrl, File file) {
if (file == null) {
return null;
}
HttpGet httpGet = new HttpGet(httpUrl);
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = null;
HttpEntity entity = null;
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
// 执行请求
response = httpClient.execute(httpGet);
entity = response.getEntity();
inputStream = entity.getContent();
fileOutputStream = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = inputStream.read(buf, 0, 1024)) != -1) {
fileOutputStream.write(buf, 0, len);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
// 关闭连接,释放资源
if (entity != null) {
// 会自动释放连接
EntityUtils.consumeQuietly(entity);
}
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
return file;
}
/**
* Post 下载文件
*
* @param httpUrl
* @param maps
* @param file
* @return
*/
public static File sendHttpPostFile(String httpUrl, Map<String, String> maps, File file) {
if (file == null) {
return null;
}
HttpPost httpPost = wrapHttpPost(httpUrl, maps);
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = null;
HttpEntity entity = null;
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
// 执行请求
response = httpClient.execute(httpPost);
entity = response.getEntity();
inputStream = entity.getContent();
fileOutputStream = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = inputStream.read(buf, 0, 1024)) != -1) {
fileOutputStream.write(buf, 0, len);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
// 关闭连接,释放资源
if (entity != null) {
// 会自动释放连接
EntityUtils.consumeQuietly(entity);
}
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
return file;
}
/**
* 判断是否微信返回错误
*
* @param jsonObject
* @return
*/
public static boolean isWxError(JSONObject jsonObject) {
if (null == jsonObject || jsonObject.getIntValue("errcode") != 0) {
return true;
}
return false;
}
/**
* http请求
*
* @param requestUrl url
* @param requestMethod GET/POST
* @param outputStr 参数
* @return
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
return httpRequest(requestUrl,requestMethod,outputStr,null);
}
/**
* http请求
*
* @param requestUrl url
* @param requestMethod GET/POST
* @param outputStr 参数
* @return
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr, String... token) {
JSONObject jsonObject = null;
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
conn.setConnectTimeout(50000);
conn.setReadTimeout(60000);
if (token != null && token.length > 2 && token[2] != null) {
if ("1".equals(token[2])) {
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE);
} else if ("2".equals(token[2])) {
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
} else if ("3".equals(token[2])) {
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
} else if ("4".equals(token[2])) {
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE);
} else {
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
}
} else {
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
}
if (token != null && token.length > 0 && StringUtil.isNotEmpty(token[0])) {
conn.setRequestProperty(Constants.AUTHORIZATION, XSSEscape.escape(token[0]));
}
// 处理请求头参数
if (token != null && token.length > 1 && StringUtil.isNotEmpty(token[1])) {
Map<String, Object> requestHeader = JsonUtil.stringToMap(token[1]);
for (String field : requestHeader.keySet()) {
conn.setRequestProperty(field, requestHeader.get(field) + "");
}
}
String agent = ServletUtil.getUserAgent();
if (StringUtil.isNotEmpty(agent)) {
conn.setRequestProperty(Constants.USER_AGENT, agent);
}
if (StringUtil.isNotEmpty(outputStr)) {
@Cleanup OutputStream outputStream = conn.getOutputStream();
outputStream.write(outputStr.getBytes(Constants.UTF8));
outputStream.close();
}
@Cleanup InputStream inputStream = conn.getInputStream();
@Cleanup InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Constants.UTF8);
@Cleanup BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
conn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
if (jsonObject == null) {
return new JSONObject();
}
} catch (Exception e) {
log.error(e.getMessage());
}
return jsonObject;
}
/**
* http请求
*
* @param requestUrl url
* @param requestMethod GET/POST
* @param outputStr 参数
* @return
*/
public static boolean httpCronRequest(String requestUrl, String requestMethod, String outputStr, String token) {
boolean falg = false;
try {
URL url = new URL(requestUrl);
final HttpURLConnection[] conn = {null};
Callable<String> task = new Callable<String>() {
@Override
public String call() throws Exception {
//执行耗时代码
try {
conn[0] = (HttpURLConnection) url.openConnection();
} catch (Exception e) {
log.error(e.getMessage());
}
conn[0].setDoOutput(true);
conn[0].setDoInput(true);
conn[0].setUseCaches(false);
conn[0].setRequestMethod(requestMethod);
conn[0].setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
if (StringUtil.isNotEmpty(token)) {
conn[0].setRequestProperty(Constants.AUTHORIZATION, token);
}
if (null != outputStr) {
@Cleanup OutputStream outputStream = conn[0].getOutputStream();
outputStream.write(outputStr.getBytes(Constants.UTF8));
outputStream.close();
}
@Cleanup InputStream inputStream = conn[0].getInputStream();
@Cleanup InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Constants.UTF8);
@Cleanup BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
conn[0].disconnect();
return "url连接ok";
}
};
Future<String> future = ThreadPoolExecutorUtil.getExecutor().submit(task);
try {
//设置超时时间
String rst = future.get(3, TimeUnit.SECONDS);
if ("url连接ok".equals(rst)) {
falg = true;
}
} catch (TimeoutException e) {
log.error("连接url超时");
} catch (Exception e) {
log.error("获取异常," + e.getMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return falg;
}
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package org.springframework.http;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.InvalidMimeTypeException;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.StringUtils;
public class MediaType extends MimeType implements Serializable {
private static final long serialVersionUID = 2069937152339670231L;
public static final MediaType ALL = new MediaType("*", "*");
public static final String ALL_VALUE = "*/*";
public static final MediaType APPLICATION_ATOM_XML = new MediaType("application", "atom+xml");
public static final String APPLICATION_ATOM_XML_VALUE = "application/atom+xml";
public static final MediaType APPLICATION_CBOR = new MediaType("application", "cbor");
public static final String APPLICATION_CBOR_VALUE = "application/cbor";
public static final MediaType APPLICATION_FORM_URLENCODED = new MediaType("application", "x-www-form-urlencoded");
public static final String APPLICATION_FORM_URLENCODED_VALUE = "application/x-www-form-urlencoded";
/** @deprecated */
@Deprecated(
since = "6.0.3",
forRemoval = true
)
public static final MediaType APPLICATION_GRAPHQL = new MediaType("application", "graphql+json");
/** @deprecated */
@Deprecated(
since = "6.0.3",
forRemoval = true
)
public static final String APPLICATION_GRAPHQL_VALUE = "application/graphql+json";
public static final MediaType APPLICATION_GRAPHQL_RESPONSE = new MediaType("application", "graphql-response+json");
public static final String APPLICATION_GRAPHQL_RESPONSE_VALUE = "application/graphql-response+json";
public static final MediaType APPLICATION_JSON = new MediaType("application", "json");
public static final String APPLICATION_JSON_VALUE = "application/json";
/** @deprecated */
@Deprecated
public static final MediaType APPLICATION_JSON_UTF8;
/** @deprecated */
@Deprecated
public static final String APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8";
public static final MediaType APPLICATION_OCTET_STREAM;
public static final String APPLICATION_OCTET_STREAM_VALUE = "application/octet-stream";
public static final MediaType APPLICATION_PDF;
public static final String APPLICATION_PDF_VALUE = "application/pdf";
public static final MediaType APPLICATION_PROBLEM_JSON;
public static final String APPLICATION_PROBLEM_JSON_VALUE = "application/problem+json";
/** @deprecated */
@Deprecated
public static final MediaType APPLICATION_PROBLEM_JSON_UTF8;
/** @deprecated */
@Deprecated
public static final String APPLICATION_PROBLEM_JSON_UTF8_VALUE = "application/problem+json;charset=UTF-8";
public static final MediaType APPLICATION_PROBLEM_XML;
public static final String APPLICATION_PROBLEM_XML_VALUE = "application/problem+xml";
public static final MediaType APPLICATION_PROTOBUF;
public static final String APPLICATION_PROTOBUF_VALUE = "application/x-protobuf";
public static final MediaType APPLICATION_RSS_XML;
public static final String APPLICATION_RSS_XML_VALUE = "application/rss+xml";
public static final MediaType APPLICATION_NDJSON;
public static final String APPLICATION_NDJSON_VALUE = "application/x-ndjson";
/** @deprecated */
@Deprecated
public static final MediaType APPLICATION_STREAM_JSON;
/** @deprecated */
@Deprecated
public static final String APPLICATION_STREAM_JSON_VALUE = "application/stream+json";
public static final MediaType APPLICATION_XHTML_XML;
public static final String APPLICATION_XHTML_XML_VALUE = "application/xhtml+xml";
public static final MediaType APPLICATION_XML;
public static final String APPLICATION_XML_VALUE = "application/xml";
public static final MediaType APPLICATION_YAML;
public static final String APPLICATION_YAML_VALUE = "application/yaml";
public static final MediaType IMAGE_GIF;
public static final String IMAGE_GIF_VALUE = "image/gif";
public static final MediaType IMAGE_JPEG;
public static final String IMAGE_JPEG_VALUE = "image/jpeg";
public static final MediaType IMAGE_PNG;
public static final String IMAGE_PNG_VALUE = "image/png";
public static final MediaType MULTIPART_FORM_DATA;
public static final String MULTIPART_FORM_DATA_VALUE = "multipart/form-data";
public static final MediaType MULTIPART_MIXED;
public static final String MULTIPART_MIXED_VALUE = "multipart/mixed";
public static final MediaType MULTIPART_RELATED;
public static final String MULTIPART_RELATED_VALUE = "multipart/related";
public static final MediaType TEXT_EVENT_STREAM;
public static final String TEXT_EVENT_STREAM_VALUE = "text/event-stream";
public static final MediaType TEXT_HTML;
public static final String TEXT_HTML_VALUE = "text/html";
public static final MediaType TEXT_MARKDOWN;
public static final String TEXT_MARKDOWN_VALUE = "text/markdown";
public static final MediaType TEXT_PLAIN;
public static final String TEXT_PLAIN_VALUE = "text/plain";
public static final MediaType TEXT_XML;
public static final String TEXT_XML_VALUE = "text/xml";
private static final String PARAM_QUALITY_FACTOR = "q";
/** @deprecated */
@Deprecated(
since = "6.0",
forRemoval = true
)
public static final Comparator<MediaType> QUALITY_VALUE_COMPARATOR;
/** @deprecated */
@Deprecated(
since = "6.0",
forRemoval = true
)
public static final Comparator<MediaType> SPECIFICITY_COMPARATOR;
public MediaType(String type) {
super(type);
}
public MediaType(String type, String subtype) {
super(type, subtype, Collections.emptyMap());
}
public MediaType(String type, String subtype, Charset charset) {
super(type, subtype, charset);
}
public MediaType(String type, String subtype, double qualityValue) {
this(type, subtype, Collections.singletonMap("q", Double.toString(qualityValue)));
}
public MediaType(MediaType other, Charset charset) {
super(other, charset);
}
public MediaType(MediaType other, @Nullable Map<String, String> parameters) {
super(other.getType(), other.getSubtype(), parameters);
}
public MediaType(String type, String subtype, @Nullable Map<String, String> parameters) {
super(type, subtype, parameters);
}
public MediaType(MimeType mimeType) {
super(mimeType);
this.getParameters().forEach(this::checkParameters);
}
protected void checkParameters(String parameter, String value) {
super.checkParameters(parameter, value);
if ("q".equals(parameter)) {
String unquotedValue = this.unquote(value);
double d = Double.parseDouble(unquotedValue);
Assert.isTrue(d >= (double)0.0F && d <= (double)1.0F, () -> "Invalid quality value \"" + unquotedValue + "\": should be between 0.0 and 1.0");
}
}
public double getQualityValue() {
String qualityFactor = this.getParameter("q");
return qualityFactor != null ? Double.parseDouble(this.unquote(qualityFactor)) : (double)1.0F;
}
public boolean isMoreSpecific(MimeType other) {
Assert.notNull(other, "Other must not be null");
if (other instanceof MediaType otherMediaType) {
double quality1 = this.getQualityValue();
double quality2 = otherMediaType.getQualityValue();
if (quality1 > quality2) {
return true;
}
if (quality1 < quality2) {
return false;
}
}
return super.isMoreSpecific(other);
}
public boolean isLessSpecific(MimeType other) {
Assert.notNull(other, "Other must not be null");
return other.isMoreSpecific(this);
}
public boolean includes(@Nullable MediaType other) {
return super.includes(other);
}
public boolean isCompatibleWith(@Nullable MediaType other) {
return super.isCompatibleWith(other);
}
public MediaType copyQualityValue(MediaType mediaType) {
if (!mediaType.getParameters().containsKey("q")) {
return this;
} else {
Map<String, String> params = new LinkedHashMap(this.getParameters());
params.put("q", (String)mediaType.getParameters().get("q"));
return new MediaType(this, params);
}
}
public MediaType removeQualityValue() {
if (!this.getParameters().containsKey("q")) {
return this;
} else {
Map<String, String> params = new LinkedHashMap(this.getParameters());
params.remove("q");
return new MediaType(this, params);
}
}
public static MediaType valueOf(String value) {
return parseMediaType(value);
}
public static MediaType parseMediaType(String mediaType) {
MimeType type;
try {
type = MimeTypeUtils.parseMimeType(mediaType);
} catch (InvalidMimeTypeException ex) {
throw new InvalidMediaTypeException(ex);
}
try {
return new MediaType(type);
} catch (IllegalArgumentException ex) {
throw new InvalidMediaTypeException(mediaType, ex.getMessage());
}
}
public static List<MediaType> parseMediaTypes(@Nullable String mediaTypes) {
if (!StringUtils.hasLength(mediaTypes)) {
return Collections.emptyList();
} else {
List<String> tokenizedTypes = MimeTypeUtils.tokenize(mediaTypes);
List<MediaType> result = new ArrayList(tokenizedTypes.size());
for(String type : tokenizedTypes) {
if (StringUtils.hasText(type)) {
result.add(parseMediaType(type));
}
}
return result;
}
}
public static List<MediaType> parseMediaTypes(@Nullable List<String> mediaTypes) {
if (CollectionUtils.isEmpty(mediaTypes)) {
return Collections.emptyList();
} else if (mediaTypes.size() == 1) {
return parseMediaTypes((String)mediaTypes.get(0));
} else {
List<MediaType> result = new ArrayList(8);
for(String mediaType : mediaTypes) {
result.addAll(parseMediaTypes(mediaType));
}
return result;
}
}
public static List<MediaType> asMediaTypes(List<MimeType> mimeTypes) {
List<MediaType> mediaTypes = new ArrayList(mimeTypes.size());
for(MimeType mimeType : mimeTypes) {
mediaTypes.add(asMediaType(mimeType));
}
return mediaTypes;
}
public static MediaType asMediaType(MimeType mimeType) {
if (mimeType instanceof MediaType mediaType) {
return mediaType;
} else {
return new MediaType(mimeType.getType(), mimeType.getSubtype(), mimeType.getParameters());
}
}
public static String toString(Collection<MediaType> mediaTypes) {
return MimeTypeUtils.toString(mediaTypes);
}
/** @deprecated */
@Deprecated(
since = "6.0",
forRemoval = true
)
public static void sortBySpecificity(List<MediaType> mediaTypes) {
Assert.notNull(mediaTypes, "'mediaTypes' must not be null");
if (mediaTypes.size() > 1) {
mediaTypes.sort(SPECIFICITY_COMPARATOR);
}
}
/** @deprecated */
@Deprecated(
since = "6.0",
forRemoval = true
)
public static void sortByQualityValue(List<MediaType> mediaTypes) {
Assert.notNull(mediaTypes, "'mediaTypes' must not be null");
if (mediaTypes.size() > 1) {
mediaTypes.sort(QUALITY_VALUE_COMPARATOR);
}
}
/** @deprecated */
@Deprecated(
since = "6.0",
forRemoval = true
)
public static void sortBySpecificityAndQuality(List<MediaType> mediaTypes) {
Assert.notNull(mediaTypes, "'mediaTypes' must not be null");
if (mediaTypes.size() > 1) {
mediaTypes.sort(SPECIFICITY_COMPARATOR.thenComparing(QUALITY_VALUE_COMPARATOR));
}
}
static {
APPLICATION_JSON_UTF8 = new MediaType("application", "json", StandardCharsets.UTF_8);
APPLICATION_NDJSON = new MediaType("application", "x-ndjson");
APPLICATION_OCTET_STREAM = new MediaType("application", "octet-stream");
APPLICATION_PDF = new MediaType("application", "pdf");
APPLICATION_PROBLEM_JSON = new MediaType("application", "problem+json");
APPLICATION_PROBLEM_JSON_UTF8 = new MediaType("application", "problem+json", StandardCharsets.UTF_8);
APPLICATION_PROBLEM_XML = new MediaType("application", "problem+xml");
APPLICATION_PROTOBUF = new MediaType("application", "x-protobuf");
APPLICATION_RSS_XML = new MediaType("application", "rss+xml");
APPLICATION_STREAM_JSON = new MediaType("application", "stream+json");
APPLICATION_XHTML_XML = new MediaType("application", "xhtml+xml");
APPLICATION_XML = new MediaType("application", "xml");
APPLICATION_YAML = new MediaType("application", "yaml");
IMAGE_GIF = new MediaType("image", "gif");
IMAGE_JPEG = new MediaType("image", "jpeg");
IMAGE_PNG = new MediaType("image", "png");
MULTIPART_FORM_DATA = new MediaType("multipart", "form-data");
MULTIPART_MIXED = new MediaType("multipart", "mixed");
MULTIPART_RELATED = new MediaType("multipart", "related");
TEXT_EVENT_STREAM = new MediaType("text", "event-stream");
TEXT_HTML = new MediaType("text", "html");
TEXT_MARKDOWN = new MediaType("text", "markdown");
TEXT_PLAIN = new MediaType("text", "plain");
TEXT_XML = new MediaType("text", "xml");
QUALITY_VALUE_COMPARATOR = (mediaType1, mediaType2) -> {
double quality1 = mediaType1.getQualityValue();
double quality2 = mediaType2.getQualityValue();
int qualityComparison = Double.compare(quality2, quality1);
if (qualityComparison != 0) {
return qualityComparison;
} else if (mediaType1.isWildcardType() && !mediaType2.isWildcardType()) {
return 1;
} else if (mediaType2.isWildcardType() && !mediaType1.isWildcardType()) {
return -1;
} else if (!mediaType1.getType().equals(mediaType2.getType())) {
return 0;
} else if (mediaType1.isWildcardSubtype() && !mediaType2.isWildcardSubtype()) {
return 1;
} else if (mediaType2.isWildcardSubtype() && !mediaType1.isWildcardSubtype()) {
return -1;
} else if (!mediaType1.getSubtype().equals(mediaType2.getSubtype())) {
return 0;
} else {
int paramsSize1 = mediaType1.getParameters().size();
int paramsSize2 = mediaType2.getParameters().size();
return Integer.compare(paramsSize2, paramsSize1);
}
};
SPECIFICITY_COMPARATOR = new MimeType.SpecificityComparator<MediaType>() {
protected int compareParameters(MediaType mediaType1, MediaType mediaType2) {
double quality1 = mediaType1.getQualityValue();
double quality2 = mediaType2.getQualityValue();
int qualityComparison = Double.compare(quality2, quality1);
return qualityComparison != 0 ? qualityComparison : super.compareParameters(mediaType1, mediaType2);
}
};
}
}
最新发布