这篇文章主要讲解了“使用apache http client调用其他服务器接口时报错怎么办”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“使用apache http client调用其他服务器接口时报错怎么办”吧!
今天在使用 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", "*/*"); 即可
以上的说法是错的。
从报错的信息就可以看出, 是 */ 这种写法 错误的。导致header accept 解析不成功。
改为
pmethod.addHeader( "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
完整版
pmethod.addHeader( "Accept", "text/html,application/xhtml+xml,application/xml;application/json,*/*;q=0.9,*/*;q=0.8");
感谢各位的阅读,以上就是“使用apache http client调用其他服务器接口时报错怎么办”的内容了,经过本文的学习后,相信大家对使用apache http client调用其他服务器接口时报错怎么办这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/ouminzy/blog/4652305