今天自己在升级公司的一个jar后,一直报空指针异常。代码如下
package com.zhuanche.http; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; import org.apache.http.*; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; 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.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import java.io.File; import java.io.InputStream; import java.nio.charset.Charset; import java.util.*; import static com.sq.common.okhttp.constants.OkHttpConfig.DEFAULT_HEADER_ACCEPT_ENCODING; import static com.sq.common.okhttp.constants.OkHttpConfig.DEFAULT_HEADER_ACCEPT_ENCODING_VALUE; import static com.sq.common.okhttp.constants.OkHttpConfig.DEFAULT_HEADER_REQLOGIGNORE; /** * 处理post请求 * @author huiwu */ public final class PostRequest extends Request{ private static final Logger logger = LoggerFactory.getLogger(PostRequest.class); private HttpPost post = null; private HttpClient client = null; private HttpEntity httpEntity = null; private final static String TRACEKEY = "X-Request-Id"; private final static String TRACEID = "traceId"; private static final String CHARNULL = ""; private final List<NameValuePair> params = new ArrayList<NameValuePair>(); private static final String DEFAULTCHARSET = "UTF-8"; private String charset = DEFAULTCHARSET; public PostRequest(HttpClient client, String url) { this.client = client;
this.addHeaders(null);
post = new HttpPost(url); } public PostRequest(HttpClient httpClient, String url, String charset) { this(httpClient,url); this.charset = charset; this.addHeaders(null); } public PostRequest addHeader(String name, Object value) { if (value == null) { return this; } if(StringUtils.isNotEmpty(name)){ post.addHeader(name, String.valueOf(value)); } return this; } public PostRequest addHeaders(Map<String,Object> headers){ //nginx统一是TRACE_KEY,项目里面有些是traceId 所以做的兼容 logger.info("tracekey:" + TRACEKEY + ",value:" + MDC.get(TRACEKEY)); addHeader(DEFAULT_HEADER_REQLOGIGNORE, String.valueOf(false)); addHeader(DEFAULT_HEADER_ACCEPT_ENCODING, DEFAULT_HEADER_ACCEPT_ENCODING_VALUE); if(MDC.get(TRACEKEY) != null){ addHeader(TRACEKEY,MDC.get(TRACEKEY)); }else if(MDC.get(TRACEID) != null){ addHeader(TRACEKEY,MDC.get(TRACEID)); }else { addHeader(TRACEKEY,CHARNULL); } if (headers==null||headers.isEmpty()) { return this; } Set<String> keySets = headers.keySet(); Iterator<String> it = keySets.iterator(); while (it.hasNext()){ String key = it.next(); addHeader(key, headers.get(key)); } return this; } public PostRequest addParam(String name, Object value) { if (value == null) { return this; } params.add(new BasicNameValuePair(name, String.valueOf(value))); return this; } public PostRequest addParams(Map<String,Object> map) { if (map == null||map.isEmpty()) { return this; } Set<String> keys = map.keySet(); Iterator<String> it = keys.iterator(); while (it.hasNext()){ String paramName = it.next(); addParam(paramName,map.get(paramName)); } return this; } /** * 设置body后,通过addParam方法添加的参数将不会设置到请求中 * @param body * @return */ public PostRequest setBody(String body) { return setBody(body,ContentType.TEXT_PLAIN); } /** * 设置body后,通过addParam方法添加的参数将不会设置到请求中 * @param body * @return */ public PostRequest setBody(String body,ContentType contentType) { try { if (body==null) { return this; } httpEntity = new StringEntity(body,charset); } catch (Exception e) { logger.error("set String body error ", e); } return this; } public PostRequest setLimitResult(int limitResult) { this.limitResult = limitResult; return this; } /** * 添加文件参数,一个POST请求添加一个文件参数 * @param name 上传文件的参数名 * @param file * @return */ public Request addFile(String name, File file) { try { addFile(name, file, ContentType.DEFAULT_BINARY); } catch (Exception e) { logger.error("set File body error ", e); } return this; } /** * 添加文件参数,一个POST请求添加一个文件参数 * @param name 上传文件的参数名 * @param file * @param contentType 默认为 application/octet-stream * @return */ public Request addFile(String name, File file,ContentType contentType) { try { if (contentType==null) { contentType = ContentType.DEFAULT_BINARY; } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody(name, file, contentType,file != null ? file.getName() : null); builder.setCharset(Charset.forName(charset)); if (params!=null&&!params.isEmpty()) { for (NameValuePair nv : params) { builder.addTextBody(nv.getName(),nv.getValue()); } } httpEntity = builder.build(); } catch (Exception e) { logger.error("set File error ", e); } return this; } public String execute()throws HttpException { return exc(String.class); } @Override public JSONObject executeToJson()throws HttpException { return exc(JSONObject.class); } public <T>T executeToObject(Class<T> clazz)throws HttpException{ return exc(clazz); } public PostRequest setIgnoreResult(boolean ignoreResult) { this.ignoreResult = ignoreResult; return this; } @SuppressWarnings("unchecked") private <T> T exc(Class<T> clazz) throws HttpException { T obj = null; int status = 0; String result = null; Integer inputSize = 0; String lbrqid = ""; String x_ca_requestid = ""; long startTime = System.currentTimeMillis(); try { if (httpEntity==null) { httpEntity = new UrlEncodedFormEntity(params,charset); } post.setEntity(httpEntity); post.setConfig(getRequestConfig()); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); try { // traceid唯一ID Header[] headers = response.getHeaders("lbrqid"); if (null != headers && headers.length > 0) { lbrqid = headers[0].getValue(); } // 阿里接口响应ID Header[] headers2 = response.getHeaders("X-Ca-Request-Id"); if (null != headers2 && headers2.length > 0) { x_ca_requestid = headers2[0].getValue(); } if(StringUtils.isEmpty(lbrqid)){ lbrqid = x_ca_requestid; } // 获取字节大小 InputStream content = entity.getContent(); inputSize = content.available(); } catch (Exception e) { logger.error("获取头信息异常.", e); } status = response.getStatusLine().getStatusCode(); if (entity!=null) { try { ContentType ct = ContentType.get(entity); result = EntityUtils.toString(entity, charset); if (clazz==null||clazz == String.class){ if (StringUtils.isNotBlank(result)){ obj = (T) result; } }else if (ContentType.APPLICATION_JSON.getMimeType().equals(ct.getMimeType())){ if (clazz == JSONObject.class){ if (StringUtils.isNotBlank(result)){ obj = (T) JSON.parseObject(result); } }else{ if (StringUtils.isNotBlank(result)){ obj = (T) JSON.parseObject(result, clazz); } } }else{ throw new RuntimeException("Not support contentType "+ ct.toString()); } }finally{ EntityUtils.consume(entity); } } } catch (Exception e) { long endTime = System.currentTimeMillis(); logger.warn("{}|{}|{}|{}|1|{}", post.getURI(), status, (endTime-startTime), inputSize, lbrqid); throw new HttpException("",e); }finally { long endTime = System.currentTimeMillis(); if (ignoreResult){ logger.info("cost={}ms,status={},url={},params={}", endTime - startTime,status, post.getURI(),params); }else{ if(limitResult <= 0 || StringUtils.defaultString(result, "").length() <= limitResult){ logger.info("cost={}ms,status={},url={},params={},result={},x_ca_requestid={}", endTime - startTime,status, post.getURI(),params,result,x_ca_requestid); }else{ result = result.substring(0, limitResult); logger.info("cost={}ms,status={},url={},params={},result={},x_ca_requestid={}", endTime - startTime,status, post.getURI(),params,result,x_ca_requestid); } } logger.warn("{}|{}|{}|{}|0|{}", post.getURI(), status, (endTime-startTime), inputSize,lbrqid); } return obj; } public PostRequest setReadTimeOut(int readTimeOut){ if (readTimeOut>0) { this.readTimeOut = readTimeOut; } return this; } public PostRequest setConnectTimeOut(int connectTimeOut){ if (connectTimeOut>0) { this.connectTimeOut = connectTimeOut; } return this; } public PostRequest setWaitTimeOut(int waitTimeOut){ if (waitTimeOut>0) { this.waitTimeOut = waitTimeOut; } return this; } }
红色部分代码一直空指针,然而自己都日志都打印出来了,入参不是空的啊。。。
想了半天,在本地调试,最后发现,是post 为空了。。 自己代码还没有new 就直接去使用了。
空指针,要么是参数问题,要么是方法里面有其他调用的参数为空。。 一下午的时间,解决了一个小问题,感觉好浪费时间。
之后打包 :mvn deploy -e 可以了。