HttpClient工具类遇到jar包冲突

上周一要写一个HttpClient工具类,用的httpcomponents-4.5.5,但是项目中pom文件中还有httpcore-4.1.2和httpclient-3.1,pom文件如下图:


然后就遇到了下面的异常:


可以看到异常是httpcomponents-4.5.5包下的ManagedHttpClientConnectionFactory类中依赖LaxContentLengthStrategy这个类,异常日志中能看出是 没有 INSTANCE这个属性的错误,然后点进去发现确实没有,但是没有INSTANCE的这个LaxContentLengthStrategy显示引用的是httpcore包中的,不是httpcomponents-4.5.5,发现类路径如下图所示:


httpcore包中的类路径如下图:


发现两个jar包类路径一样,项目默认加载了httpcore包中的类。猜想可能httpcommonents包和httpcore、httpclient包冲突了,通过mvn命令查看jar包依赖关系,如下图:


确实存在jar包依赖关系。查看jar包依赖关系也可以通过idea查看,在pom文件中,右键->Diagrams->Show Dependences

扫描二维码关注公众号,回复: 1030603 查看本文章


最后的解决办法:把pom文件中只留下了httpcommonents-4.5.5这个包,把另外两个都去掉了。

代码:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Http工具类
 */
public class HttpUtil {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    private static final int SUCCESS_STATUS = 200;

    public static JSONObject doPostJson(String url, String json, String token) {

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json);
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            httpPost.setHeader("Authorization", token);
            httpPost.setEntity(s);
            HttpResponse res = client.execute(httpPost);
            if (SUCCESS_STATUS == res.getStatusLine().getStatusCode()) {
                String result = EntityUtils.toString(res.getEntity());
                response = JSON.parseObject(result);
            } else {
                String result = EntityUtils.toString(res.getEntity());
                response = JSON.parseObject(result);
                System.out.println("返回异常结果:" + response.toString());
                return response;
            }
        } catch (Exception e) {
            logger.error("异常:" + e);
        }
        return response;

    }
}

猜你喜欢

转载自blog.csdn.net/dam454450872/article/details/80376028
今日推荐