今天在使用 apache http client 调用 其他服务器的接口的时候, get 请求报错了
org.springframework.web.HttpMediaTypeNotAcceptableException:
Could not parse ‘Accept‘ header [text/html,application/xhtml+xml,application/xml;q=0.9,*/;q=0.8]: Invalid mime type "*/;q=0.8": does not contain subtype after ‘/‘
org.springframework.util.InvalidMimeTypeException:
Invalid mime type "*/;q=0.8": does not contain subtype after ‘/‘
说是不支持 header 的 accept 类型。 因为这个 服务器的接口默认只支持返回 json 格式的。所以报错了,修改 http client 的请求header 的 acept 即可
代码如下:
/**
* GET方式提交数据
*
* @param url 待请求的URL
* @param params 要提交的数据
* @param enc 编码
* @param resEnc 响应内容的编码
* @return 响应结果
*/
public static String doGet(String url, Map<String, String> params, String enc, String resEnc) {
String response = EMPTY;
HttpGet getMethod = null;
if (StringUtils.isEmpty(url)) {
return null;
}
StringBuffer strtTotalURL = getTotalUrl(url, params, enc);
logger.debug("GET请求URL = \n" + strtTotalURL.toString());
try {
getMethod = getGetMethod(strtTotalURL.toString());
getMethod.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + enc);
// 执行getMethod
HttpResponse httpResponse = getHttpClient(url).execute(getMethod);
response = getResponse(url, httpResponse, resEnc);
} catch (ClientProtocolException e) {
logger.error("发生致命的异常,可能是协议不对或者返回的内容有问题" + e.getMessage(), e);
} catch (IOException e) {
logger.error("发生网络异常" + e.getMessage(), e);
} finally {
if (getMethod != null) {
getMethod.releaseConnection();
getMethod = null;
}
}
return response;
}
/**
* 模拟浏览器GET提交
*
* @param url
* @return
*/
private static HttpGet getGetMethod(String url) {
if (!url.startsWith(HTTP)) {
url = "http://" + url;
}
HttpGet pmethod = new HttpGet(url);
// 设置响应头信息
pmethod.addHeader("Connection", "keep-alive");
pmethod.addHeader("Cache-Control", "max-age=0");
pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
// pmethod.addHeader("Accept",
// "text/html,application/xhtml+xml,application/xml;q=0.9,*/;q=0.8");
// 设置接收所有类型的,否则如果请求的服务器只支持 application/json 那么就会报错
pmethod.addHeader("Accept", "*/*");
return pmethod;
}
改为 pmethod.addHeader("Accept", "*/*"); 即可
来源:天津SEO
Invalid mime type "*/;q=0.8": does not contain subtype after '/'
原文:https://www.cnblogs.com/plus666/p/13742587.html