public class CommonUtil{
private static Logger log = LoggerFactory.getLogger(CommonUtil.class);html
// 凭证获取(GET)
public final static String accessToken_url = WeiXinConstant.GET_ACCESSTOKEN_URL;java
public static String getRespContentFromWXByHttp(String wxUrl,String method,String mediaId) {
FileOutputStream out=null;
InputStream in =null;
try{
String dir=System.getProperty("user.dir")+WeiXinConstant.WX_UPLOAD_FILE_PATH+File.separator;
log.info("dir:"+ dir);
if(!new File(dir).exists()){
new File(dir).mkdirs();
log.info("建立上传文件夹!"+System.getProperty("user.dir"));
}
URL url = new URL(wxUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestMethod(method);
conn.connect();
in = conn.getInputStream();
//获取微信文件名
String picName="";
String contentDisposition =conn.getHeaderField("Content-Disposition");
log.info("从微信端下载图片信息为:类型为"+conn.getContentType()+",大小:"+conn.getContentLength());
if(StringUtils.checkStr(contentDisposition)){
Pattern p=Pattern.compile("[\"\\?!:'<>]");//增长对应的标点
Matcher m=p.matcher(contentDisposition.split("filename=")[1]);
picName=m.replaceAll("");
}
String fileName="";
if(StringUtils.checkStr(picName)){
fileName=dir+picName;
}else{
fileName=dir+mediaId+".jpg";
}
out=new FileOutputStream(fileName);
int len=0;
byte[] b=new byte[1024];
while((len=in.read(b))!=-1){
out.write(b, 0, len);
}
log.info("文件本地下载完毕!"+fileName);
return fileName;
}catch (Exception e) {
log.error("上传微信图片失败:" + e.getMessage());
return null;
}finally{
try {
out.flush();
out.close();
in.close();
} catch (IOException e) {
log.error("上传微信图片失败:" + e.getMessage());
}
}
}
/**
* 发送https请求
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(经过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
try {
// 建立SSLContext对象,并使用咱们指定的信任管理器初始化
TrustManager[] tm = { new SslUtil.miTM() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中获得SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();git
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);ajax
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}json
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}api
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
log.error("链接超时:{}", ce);
} catch (Exception e) {
log.error("https请求异常:{}", e);
}
return jsonObject;
}数组
/**
* 获取接口访问凭证
*
* @return
*/
public static AccessToken getAccessToken() {
AccessToken accessToken = null;
String requestUrl = accessToken_url.replace("APPID", WeiXinConstant.APPID).replace("APPSECRET", WeiXinConstant.APPSECRET);
// 发起GET请求获取凭证
JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);服务器
if (null != jsonObject) {
try {
accessToken = new AccessToken();
accessToken.setAccessToken(jsonObject.getString("access_token"));
accessToken.setTokenExpires(jsonObject.getInt("expires_in"));
} catch (JSONException e) {
accessToken = null;
// 获取accessToken失败
log.error("获取accessToken失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
return accessToken;
}
/**
* URL编码(utf-8)
*
* @param source
* @return
*/
public static String urlEncodeUTF8(String source) {
String result = source;
try {
result = java.net.URLEncoder.encode(source, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
}微信
/**
* 请求校验工具类
*
* @author
*/
public class SignUtil{
// 与开发模式接口配置信息中的Token保持一致
private static String token = WeiXinConstant.TOKEN;app
/**
* 校验签名
*
* @param signature 微信加密签名
* @param timestamp 时间戳
* @param nonce 随机数
* @return
*/
public static boolean checkSignature(String signature, String timestamp,
String nonce) {
// 对token、timestamp和nonce按字典排序
String[] paramArr = new String[] { token, timestamp, nonce };
Arrays.sort(paramArr);
// 将排序后的结果拼接成一个字符串
String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);
String ciphertext = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
// 对接后的字符串进行sha1加密
byte[] digest = md.digest(content.toString().getBytes());
ciphertext = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 将sha1加密后的字符串与signature进行对比
return ciphertext != null ? ciphertext.equals(signature.toUpperCase())
: false;
}
/**
* 将字节数组转换为十六进制字符串
*
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = 0; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* 将字节转换为十六进制字符串
*
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F' };
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
}
public class WeiXinJsConfigUtil {
public static final Logger log = Logger.getLogger(WeiXinJsConfigUtil.class);
public static WeiXinConfigVo sign(String jsapi_ticket, HttpServletRequest request) {
StringBuffer url = request.getRequestURL();
if (request.getQueryString() != null) {
url.append("?");
url.append(request.getQueryString());
}
log.info("获取jsapi_ticket的地址为:----"+url);
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
String string1;
String signature = "";
//注意这里参数名必须所有小写,且必须有序
string1 = "jsapi_ticket=" + jsapi_ticket +
"&noncestr=" + nonce_str +
"×tamp=" + timestamp +
"&url=" + url;
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(string1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
WeiXinConfigVo weixinConfigVo=new WeiXinConfigVo();
weixinConfigVo.setTimestamp(timestamp);
weixinConfigVo.setNonceStr(nonce_str);
weixinConfigVo.setSignature(signature);
log.info("signature="+signature);
return weixinConfigVo;
}
private static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
private static String create_nonce_str() {
return UUID.randomUUID().toString();
}
private static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
}
@Controller
@RequestMapping(value = "/wx")
public class PictureUploadWxController {
private Log log = LogFactory.getLog(this.getClass());
@Resource(name = "weiXinService")
private WeiXinService weiXinService;
/**
* 从本地上传到文件服务器
*
* @param fileName
* @return
*/
public JSONObject uploadImage(String fileName) {
File file = new File(fileName);
String timestamp = new Date().getTime() + "";
String sign = MD5.encryption(timestamp
+ "9k3#8j");
// String sign=MD5.encryption(timestamp+"lk#kdlw");
// String
// url="http://upload.t.dbn.cn/publicUploadServlet"+"?timestamp="+timestamp+"&uploadSource=public&sign="+sign;
String url = PropertiesUtils
.getProperty("fileServerUrl")
+ "?timestamp="
+ timestamp
+ "&uploadSource=mall"
+ "&sign=" + sign;
log.info("拼URL:"+url);
Map<String, String> param = new HashMap<String, String>();
// 是否压缩
param.put("thumbnail", "true");
param.put("width", "800");
param.put("height", "800");
JSONObject json = HttpClientUtil.postFile(url, file, file.getName(),
param);
log.info("上传文件服务器返回json" + json);
// ret返回状态,0为正常返回
if (null != json && "0".equals(json.getString("ret"))) {
return json;
}
return null;
}
/*
* 把微信图片放到农信服务器
*/
@RequestMapping("/toPigUpload")
@ResponseBody
public Map<String, Object> toPigUpload(GoodsEntity goods, ModelMap modelMap,
HttpServletRequest request, HttpServletResponse response) throws Exception {
if (goods == null) {
goods = new GoodsEntity();
}
Map<String, Object> map = new HashMap<String, Object>();
try {
String mediaId = request.getParameter("serverId");
String access_token = request.getParameter("accessToken");
String wxUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
+ access_token + "&media_id=" + mediaId;
log.info("url" + wxUrl);
String fileName;
fileName = CommonUtil.getRespContentFromWXByHttp(wxUrl, "GET",
mediaId);
log.info("fileName:" + fileName);
// 上传图片至文件服务器
JSONObject json = this.uploadImage(fileName);
log.info("文件上传完毕!返回JSON信息" + json);
String pigImgPath = PropertiesUtils
.getProperty(GoodsConstants.FILE_IMG_URL_PREFIX);// 生猪图片存储路径
String path=null;
if (null != json
&& StringUtils.checkStr(json.getString("filepath"))) {
log.info("文件服务器返回路径原图片:"+ json.getString("filepath"));
log.info("文件服务器返回路径压缩后图片:"+ json.getString("smallIcon"));
path = URLDecoder.decode(json.getString("filepath"), "utf-8");
path = path.replaceAll(pigImgPath,"");
// 上传完毕后删除图片
FileUtils.deleteQuietly(new File(fileName));
map.put("path", path);
log.info("path"+path);
}
} catch (Exception e1) {
log.error("保存微信端图片失败" + e1.getMessage());
return null;
}
String step = request.getParameter("step");
map.put("step", step);
log.info("step:"+step);
return map;
}
}
//调用微信照片接口相关js
var picnum=0;
var serverId = "";
var accessToken = "";
$(document).ready(function(){
$("#weixinPhotoIds").val("");
picnum=0;
serverId = "";
$('#chooseImage').click (function () {
chooseImage();
});
});
wx.config({
debug: false,
appId: $("#appId").val(),
timestamp: $("#timestamp").val(),
nonceStr: $("#nonceStr").val(),
signature: $("#signature").val(),
jsApiList: [
'chooseImage',
'previewImage',
'uploadImage',
'downloadImage'
]
});
function chooseImage(){
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
success: function (res) {
var localIds = res.localIds;
if(picnum+localIds.length>3){
dialogalert('','最多可上传3张!');
return;
}
var i = 0, length = localIds.length;
//上传到微信服务器
function upload() {
wx.uploadImage({
localId: localIds[i],
isShowProgressTips: 3,
success: function (res) {
serverId += res.serverId+ ",";
$("#weixinPhotoIds").val(serverId);
showpic(localIds[i],res.serverId);
accessToken = $("#accessToken").val();
localupload(res.serverId);
i++;
if (i < length) {
upload();
}
}
});
}
upload();
}
});
}
function showpic(localId,resId){
if(picnum==3){
dialogalert('','最多可上传3张!');
return;
}
var html="<li id='"+resId+"'> <img style='width:110px;height:110px' src='"+localId+"' /> <p><a style='cursor:pointer' onclick=\"del('"+resId+"');\">删除</a></p> </li>";
if(picnum==2){
$("#addFileBtn").hide();
$("#addFileBtn").before(html);
}else{
$("#addFileBtn").before(html);
}
picnum++;
}
function del(resId){
$("#"+resId).remove();
serverId=serverId.replace(resId+",","");
$("#weixinPhotoIds").val(serverId);
$("#addFileBtn").show();
picnum--;
}
function localupload(serverId){
var step = $("#step").val();
var param = {
step:step,
};
$.ajax({
url : contextPath + "/wx/toPigUpload.do?accessToken="+accessToken+"&serverId="+serverId,
type : "POST",
data : param,
dataType : "json",
contentType : "application/jsonp; charset=utf-8",
jsonp : "cb",
success : function(data) {
console.log(data);
if(picnum==1){
$("#img1").val(data.path);
}else{
if(picnum==2){
$("#img2").val(data.path);
}else{
$("#img3").val(data.path);
}
}
}
});
}
wx.error(function(res){
dialogalert('',"微信调用失败:"+res.errMsg);
});
function nextToThird() {
$("#form").attr('action', contextPath + "/mob/goods/boar/step3.do");
$("#form").submit();
}
function cancle(){ var categoryId = $("#categoryId").val(); window.location.href=contextPath+"/mob/goods/boar/step1.do?categoryId="+categoryId;}