用httpClient写了一段向其他网站发送http请求的代码。同一个项目,同一段代码,import也是一样的。我将代码放在Main方法里面正常运行,但是放在servlet 的doGet()方法里面,通过访问某个页面触发这段代码就报错了 java.lang.NoClassDefFoundError: org/apache/http/protocol/HttpContext请问各位大佬这是什么原因?
String html = HttpUtils.sendGet("https://passport.csdn.net/account/login");  //单独拿出来的报错的语句
class HttpUtils { private static CloseableHttpClient httpClient = HttpClients.createDefault();
private static HttpClientContext context = new HttpClientContext();
private static String token;
private HttpUtils() { }

public static String getToken() {
return token;
}

public static String sendGet(String url) {
CloseableHttpResponse response = null;
String content = null;
try {
HttpGet get = new HttpGet(url);
// get.setHeader("Cookie", getToken());
response = httpClient.execute(get, context);
HttpEntity entity = response.getEntity();
content = EntityUtils.toString(entity);
EntityUtils.consume(entity);
return content;
} catch (Exception e) {
e.printStackTrace();
if (response != null) {
try {
response.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return content;
} public static String sendPost(String url, List<NameValuePair> nvps) {
CloseableHttpResponse response = null;
String content = null;
try {
// HttpClient中的post请求包装类
HttpPost post = new HttpPost(url);
// nvps是包装请求參数的list
if (nvps != null) {
post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
}
// 运行请求用execute方法,content用来帮我们附带上额外信息
response = httpClient.execute(post, context);
HeaderIterator it = response.headerIterator();
while(it.hasNext()) {
// System.out.println(it.next());
String str = it.next().toString();
if(str.contains("access-token")) {
token = str.split(";")[0].split(": ")[1];
System.out.println(token);
}
}
// 得到对应实体、包含响应头以及对应内容
HttpEntity entity = response.getEntity();
// 得到response的内容
content = EntityUtils.toString(entity);
// 关闭输入流
EntityUtils.consume(entity);
return content;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content;
}
}

解决方案 »

  1.   

    war包中包含第三方jar包吗这个工具类写的有不能并发。两个servlet同时调用这个类,就会相互干扰。方法,属性,特别是session,一定不能静态。调用的时候一定要创建独自的实例,再使用,这样才能保证属性私有。
      

  2.   


    嗯嗯,这个我后期会改,但是现在遇到这个问题我调了一天了都解决不了。这是我引入的jar包
      

  3.   


    我现在将HttpUtils里面的所有static都去掉了,也改成了实例化HttpUtils进行操作,不过还是同样的问题
      

  4.   


    嗯嗯,这个我后期会改,但是现在遇到这个问题我调了一天了都解决不了。这是我引入的jar包怀疑你引用的jar没有打入war,用压缩软件打开war包看看。
    把引用换成maven依赖