首页

解决httpcore-4.2.2.jar包引用冲突引起java.lang.NoSuchFieldError: INSTANCE报错问题

标签:NoSuchFieldError,httpcore,htmlunit,OSGi,错误异常     发布时间:2018-01-10   

一、错误描述

基于apache的org.apache.http.impl.client.HttpClients发起Post提交访问,在实例化CloseableHttpClient的时候报出“java.lang.NoSuchFieldError: INSTANCE”异常问题,示例demo如下所示

import org.apache.http.HttpEntity;@b@import org.apache.http.HttpResponse;@b@import org.apache.http.client.methods.HttpPost;@b@import org.apache.http.entity.StringEntity;@b@import org.apache.http.impl.client.CloseableHttpClient;@b@import org.apache.http.impl.client.HttpClients;@b@import org.apache.http.util.EntityUtils;@b@@b@public class HttpSSLClientDemo {@b@@b@    private static String apiURL = "http://www.xwood.net/api/access";@b@@b@    public static String httpPostWithJSON(String url) throws Exception {@b@        HttpPost post = new HttpPost(url);@b@        CloseableHttpClient client = HttpClients.createDefault();@b@        String responseBody = null;//响应体@b@        String param = "{\"id\":\"20171218172330\"}";@b@        StringEntity entity = new StringEntity(param,"utf-8");@b@        entity.setContentEncoding("UTF-8");@b@        entity.setContentType("application/json");@b@        post.setEntity(entity);@b@@b@        HttpResponse response = client.execute(post);@b@        if(response.getStatusLine().getStatusCode() == 200) {@b@            HttpEntity he = response.getEntity();@b@            responseBody = EntityUtils.toString(he,"UTF-8");@b@        }@b@        return responseBody;@b@    }@b@@b@    public static void main(String[] args) throws Exception {@b@        String result = httpPostWithJSON(apiURL);@b@        System.out.println(result);@b@    }@b@}

二、解决办法

这个因为项目同时引入了htmlunit-2.15-OSGi.jar和httpcore-4.2.2.jar两个jar包都包含“org.apache.http.impl.client.HttpClients”、“org.apache.http.impl.client.CloseableHttpClient”及相关依赖类,去掉httpcore-4.2.2.jar包,重新运行问题解决了。

<<热门下载>>