一、
pom.xml文件里面加入:commons-httpclient.jar
<dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>
/** * post 请求 * * @param url * @param paramsMap * @return */ public static String doPostJson(String url, Map<String, Object> paramsMap,String accessToken) { String rep = ""; try { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); method.setRequestHeader("Content-Type", "application/json;charset=utf-8"); if(StringUtils.isNotEmpty(accessToken)){ method.setRequestHeader("Authorization", "Bearer " +accessToken); } HttpMethodParams params = method.getParams(); params.setContentCharset("utf-8"); RequestEntity entity = new StringRequestEntity(JSON.toJSONString(paramsMap), "application/json", "UTF-8"); method.setRequestEntity(entity); //设置连接超时时间 client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); //读取超时时间 client.getHttpConnectionManager().getParams().setSoTimeout(10000); //设置POST方法请求超时 method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000); int status = client.executeMethod(method); if (status == 200) { rep = method.getResponseBodyAsString(); } method.releaseConnection(); } catch (Exception e) { e.printStackTrace(); log.error("error", e); } return rep; }
二、
pom.xml文件里面加入:org.nutz.jar
<dependency> <groupId>org.nutz</groupId> <artifactId>nutz</artifactId> <version>${nutz.version}</version> </dependency>
/** * 查询快递信息 * * @param com 快递公司代码 * @param nu 快递单号 * @param key * @return 返回json字符串 */ public static String getExpressInfo(String com, String nu, String key) { try { StringBuilder sb = new StringBuilder(); sb.append("http://api.kuaidi100.com/api?id=").append(key); sb.append("&com=").append(com); sb.append("&nu=").append(nu); sb.append("&show=0&muti=1&order=desc"); Request req = Request.create(sb.toString(), Request.METHOD.GET); Response resp = Sender.create(req).send(); if (resp.isOK()) { return resp.getContent(); } } catch (Exception e) { log.error("快递查询错误:" + e.getMessage()); } return ""; }