调用 工具类的时候 报错 java.lang.NoClassDefFoundError :INSTANCE
jar 包也没有冲突 在调用执行 HttpClientBuilder.create().build(); 方法时 就会出现
调用 工具类的时候 报错 java.lang.NoClassDefFoundError :INSTANCE
jar 包也没有冲突 在调用执行 HttpClientBuilder.create().build(); 方法时 就会出现
收起
当前问题酬金
¥ 0 (可追加 ¥500)
支付方式
扫码支付
那就是jar包没有导入嘛
你是不是导错了包。没有的话,换这个版本试试。
我给你发一份工具包。
import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
public class HttpClientUtils {
private static Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class);
public static String doGet(String url, Map<String, String> params, Map<String, String> headers) throws Exception {
return doGet(url + (setGetParams(params, false)), headers);
}
public static String doGet(String url, Map<String, String> headers) throws Exception {
// 创建Httpclient对象
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
// 创建Http Get请求
HttpGet httpPost = new HttpGet(url);
httpPost.setConfig(getRequestConfig());
if (headers != null) {
Header[] allHeader = new BasicHeader[headers.size()];
int i = 0;
for (Map.Entry<String, String> entry : headers.entrySet()) {
allHeader[i] = new BasicHeader(entry.getKey(), entry.getValue());
i++;
}
httpPost.setHeaders(allHeader);
}
// 执行http请求
response = httpClient.execute(httpPost);
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
org.apache.http.client.utils.HttpClientUtils.closeQuietly(response);
}
}
private static String setGetParams(Map<String, String> params, boolean isWH) throws UnsupportedEncodingException {
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : params.keySet()) {
if (params.get(key) == null)
continue;
if (i == 0)
if (isWH) {
param.append("&");
} else {
param.append("?");
}
else
param.append("&");
param.append(key).append("=").append(urlEncode(String.valueOf(params.get(key))));
i++;
}
return param.toString();
}
private static String urlEncode(String value) throws UnsupportedEncodingException {
return URLEncoder.encode(value, "utf-8");
}
public static String doPost(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
return doPost(url, params == null ? null : JSON.toJSONString(params), headers);
}
public static String doPost(String url, String requestStr, Map<String, String> headers) throws Exception {
// 创建Httpclient对象
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(getRequestConfig());
if (headers != null) {
Header[] allHeader = new BasicHeader[headers.size()];
int i = 0;
for (Map.Entry<String, String> entry : headers.entrySet()) {
allHeader[i] = new BasicHeader(entry.getKey(), entry.getValue());
i++;
}
httpPost.setHeaders(allHeader);
}
// 创建参数列表
if (!StringUtils.isEmpty(requestStr)) {
StringEntity entity = new StringEntity(requestStr, "UTF-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
org.apache.http.client.utils.HttpClientUtils.closeQuietly(response);
}
}
public static String doPostFile(String url, Map<String, String> paramMap, Map<String, String> headers, MultipartFile file) throws Exception {
// 创建Httpclient对象
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
if (headers != null) {
Header[] allHeader = new BasicHeader[headers.size()];
int i = 0;
for (Map.Entry<String, String> entry : headers.entrySet()) {
allHeader[i] = new BasicHeader(entry.getKey(), entry.getValue());
i++;
}
httpPost.setHeaders(allHeader);
}
MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
if (paramMap != null && !paramMap.isEmpty()) {
Iterator<String> iterator = paramMap.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
mEntityBuilder.addPart(key, new StringBody(paramMap.get(key), ContentType.TEXT_PLAIN));
}
}
ContentType contentType = ContentType.create(file.getContentType());
ContentBody ContentBody = new InputStreamBody(file.getInputStream(), contentType, file.getOriginalFilename());
mEntityBuilder.addPart("file", ContentBody);
httpPost.setEntity(mEntityBuilder.build());
response = httpClient.execute(httpPost);
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
org.apache.http.client.utils.HttpClientUtils.closeQuietly(response);
}
}
private static RequestConfig getRequestConfig() {
return RequestConfig.custom().setConnectTimeout(10 * 1000) //连接超时时间
.setConnectionRequestTimeout(1000) //从连接池中取的连接的最长时间
.setSocketTimeout(10 * 1000) //数据传输的超时时间
.build();
}
public static byte[] downloadFile(String url) throws Exception {
// 创建Httpclient对象
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
InputStream in = null;
try {
httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
in = entity.getContent();
long length = entity.getContentLength();
if (length <= 0) {
return null;
}
return IOUtils.toByteArray(in);
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
org.apache.http.client.utils.HttpClientUtils.closeQuietly(response);
}
}
public static String sendPost(String url, Map<String, String> params) {
String send_url = url;
LOGGER.info("sendUrl:" + send_url + "\t\tparams:" + params);
PostMethod post = new PostMethod(send_url);
String result = null;
try {
post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 1000 * 60 * 10);
setPostParams(post, params);
result = send(post);
LOGGER.info("result:" + result);
} catch (Exception e) {
LOGGER.error("", e);
throw new RuntimeException(e);
} finally {
post.releaseConnection();// 释放连接
}
return result;
}
/**
* 发送请求
*
* @param method
* @return
* @throws IOException
*/
private static String send(HttpMethod method) throws IOException {
HttpClient httpClient = new HttpClient();
httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 1000 * 60 * 10);
httpClient.executeMethod(method);
String s = null;
try {
s = method.getResponseBodyAsString();
} catch (Exception e) {
LOGGER.error("", method.getURI());
throw new RuntimeException(e);
}
return s;
}
/**
* 设置post参数
*
* @param method
* @param params
* @throws UnsupportedEncodingException
*/
public static void setPostParams(PostMethod method, Map<String, String> params) throws UnsupportedEncodingException {
if (params != null) {
for (Iterator<String> tor = params.keySet().iterator(); tor.hasNext(); ) {
String key = tor.next();
String value = params.get(key) == null ? "" : String.valueOf(params.get(key));
method.addParameter(key, value);
}
}
}
}
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632
非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!
速戳参与调研>>>https://t.csdnimg.cn/Kf0y
除了引入了httpclient的包,还有哪些其他的包,把你的pom.xml文件里面的依赖贴出来看下。
报告相同问题?