JAVA通过URL调用第三方接口返回ClientProtocolException或者invalid http response
本人与第三方华为ocx控件对接,后台使用http工具类调用华为接口,获取坐席状态,如(http://ip:port//method?methodname\=getSkillsAgentlist¶m\=1),此工具为HttpClientPostUtil,项目中都是用这个工具类来调用第三方URL接口获取返回数据的。这两天遇到一个很奇怪的问题,调用其它URL接口正常,调用此华为接口要么报ClientProtocolException异常,要么invalid http response。网上查阅资料,解决方案是头部增加USER_AGENT设置,或者自定义类,当接口返回错误头部信息也正常返回。自己本身也通过更换工具类或者用post或get请求,都无功而返。用URL抓包工具时,弹出协议出入警告,但是可以正常获取返回数据。如在IE浏览器直接访问URL地址,可正常看到返回数据,Chrome浏览器返err_invalid_http_response。排查一天之后,定位代码没有问题,之后排查服务器环境,也没有问题。通过查看log日志后,发现接口返回数据无Header信息,协调第三方增加协议头部信息,问题解决。
工具类代码如下
package cn.sh.ideal.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
public class HttpClientPostUtil{
private static Logger log=Logger.getLogger(HttpClientPostUtil.class);
public HttpClientPostUtil(){
super();
}
/**
* post方法
* @param url http请求url连接地址和url传参
* @param 表单传参
*/
public static String postMapParams(String url,Map<String, String> parammap){
String body = null;
HttpPost post = null;
CloseableHttpResponse httpresponse = null;
CloseableHttpClient client = HttpClients.createDefault();
try {
//连接时间20s
//数据传输时间60s
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(20000).build();
if(StringUtils.isBlank(url) || !url.startsWith("http")){
log.error("请求地址格式不对:"+url);
return body;
}
post = new HttpPost(url);
//设置超时
post.setConfig(requestConfig);
//创建表单参数
if(parammap!=null&¶mmap.size()>0){
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for(String key:parammap.keySet()){
formparams.add(new BasicNameValuePair(key, parammap.get(key)));
}
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
post.setEntity(uefEntity);
}
// 发送请求
httpresponse = client.execute(post);
int statusCode = httpresponse.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode) {
// 获取返回数据
HttpEntity entity = httpresponse.getEntity();
body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} else{
log.error("http请求状态码:"+statusCode);
}
httpresponse.close();
} catch (Exception e) {
log.error("http请求失败:"+url);
log.error(e);
}finally {
if(httpresponse!=null){
try {
httpresponse.close();
} catch (IOException e) {
log.error(e);
}
}
if(post!=null&&!post.isAborted()){
post.releaseConnection();
}
if(client!=null){
try {
client.close();
} catch (IOException e) {
log.error(e);
}
}
}
return body;
}
/**
* post方法
* @param url http请求url连接地址
* @param json传参
*/
public static String postJsonParams(String url,String parammap){
String body = null;
HttpPost post = null;
CloseableHttpResponse httpresponse = null;
CloseableHttpClient client = HttpClients.createDefault();
String encoderJson = "";
try {
if(parammap != null && !"".equals(parammap))
encoderJson = URLEncoder.encode(parammap, "UTF-8");
} catch (UnsupportedEncodingException e1) {
log.error(e1);
}
try {
//连接时间20s
//数据传输时间60s
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(20000).build();
if(StringUtils.isBlank(url) || !url.startsWith("http")){
log.error("请求地址格式不对:"+url);
return body;
}
post = new HttpPost(url);
//设置超时
post.setConfig(requestConfig);
post.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0; .NET CLR 2.0.50727; SLCC2; .NET4.0C; .NET4.0E)");
post.setHeader("Content-type","text/html;charset=utf-8");
post.setHeader("Accept", "*/*");
post.setHeader("Accept-Encoding", "gzip, deflate");
post.setHeader("Accept-Language", "zh-CN");
post.setEntity(new StringEntity(encoderJson));
// 发送请求
httpresponse = client.execute(post);
int statusCode = httpresponse.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode) {
// 获取返回数据
HttpEntity entity = httpresponse.getEntity();
body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} else{
log.error("http请求状态码:"+statusCode);
}
httpresponse.close();
} catch (Exception e) {
log.error("http请求失败:"+url);
log.error(e);
}finally {
if(httpresponse!=null){
try {
httpresponse.close();
} catch (IOException e) {
log.error(e);
}
}
if(post!=null&&!post.isAborted()){
post.releaseConnection();
}
if(client!=null){
try {
client.close();
} catch (IOException e) {
log.error(e);
}
}
}
return body;
}
}