Commit 3f6f81a9 authored by TianYh's avatar TianYh

'tyh'

parent fb060ed2
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
<classpathentry kind="lib" path="lib/classes12.jar"/>
<classpathentry kind="lib" path="lib/commons-beanutils.jar"/>
<classpathentry kind="lib" path="lib/ezmorph-1.0.jar"/>
<classpathentry kind="lib" path="lib/json-lib-2.3-jdk15.jar"/>
<classpathentry kind="lib" path="lib/commons-httpclient-3.1.jar"/>
<classpathentry kind="lib" path="lib/commons-codec-1.4.jar"/>
<classpathentry kind="lib" path="lib/commons-collections.jar"/>
<classpathentry kind="lib" path="lib/commons-lang.jar"/>
<classpathentry kind="lib" path="lib/commons-logging-1.1.1.jar"/>
<classpathentry kind="lib" path="D:/apache-tomcat-6.0.44/lib/servlet-api.jar"/>
<classpathentry kind="lib" path="E:/libs/commons-collections-3.1.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>hls_plugin_weixin</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6
oracleDriver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@10.0.36.97:1521:hls
# url=jdbc:oracle:thin:@172.20.0.115:1521:hls
username=hls_standard
password=hls_standard
\ No newline at end of file
package hls.plugin.weixin.common;
import hls.plugin.weixin.qiye.DBUtil;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class GetPropertiesValue {
public Map<String, String> GetValue(){
Map<String, String> map=new HashMap<String, String>();
Properties prop = new Properties();
InputStream in = null;
in = new DBUtil().getPathName("hls/plugin/weixin/qiye/constants.properties");
try {
prop.load(in);
map.put("appid", prop.getProperty("appid"));
map.put("secret", prop.getProperty("secret"));
map.put("winXinSavePath", prop.getProperty("weiXinSavePath"));
map.put("zuLinsavePath", prop.getProperty("zuLinsavePath"));
map.put("weixinserviceUrl", prop.getProperty("weixinserviceUrl"));
map.put("zuLinserviceUrl", prop.getProperty("zuLinserviceUrl"));
map.put("file_type_code", prop.getProperty("file_type_code"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return map;
}
}
package hls.plugin.weixin.common;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
public class HttpUtil {
public static String httpRequestUrl(String requestUrl,String method){
HttpClient client=new HttpClient();
HttpMethod httpMethod=null;
String responseMessage="";
if("GET".equals(method)){
httpMethod=new GetMethod(requestUrl);
}else{
httpMethod = new PostMethod(requestUrl);
try {
} catch (Exception e) {
e.printStackTrace();
}
}
try {
client.executeMethod(httpMethod);
} catch (HttpException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
responseMessage = httpMethod.getResponseBodyAsString();
httpMethod.releaseConnection();
} catch (IOException e) {
e.printStackTrace();
}
return responseMessage;
}
}
package hls.plugin.weixin.fuwu;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import hls.plugin.weixin.common.GetPropertiesValue;
import hls.plugin.weixin.common.HttpUtil;
public class GetOpenid {
public String getAccessTokenURL(String code, String appid,
String secret) {
String mutiurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
+ appid
+ "&secret="
+ secret
+ "&code="
+ code
+ "&grant_type=authorization_code";
return mutiurl;
}
public String run(String code, String appid, String secret) {
String openid = "";
GetPropertiesValue gp = new GetPropertiesValue();
String requestUrl = getAccessTokenURL(code, appid, secret);
JSONObject jsonObject = JSONObject.fromObject(HttpUtil.httpRequestUrl(
requestUrl, "GET")); // Http GET
// ɹ
if (null != jsonObject) {
try {
openid = jsonObject.getString("openid");
} catch (JSONException e) {
openid = null;
}
}
return openid;
}
}
package hls.plugin.weixin.fuwu;
import hls.plugin.weixin.common.HttpUtil;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class ServiceUtil {
public static String getAccessCodeURL(String appid,String redirect_uri,String state){
String mutiurl="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_base&state="+state+"#wechat_redirect";
return mutiurl;
}
/**
* 手机发起请求
* @param redirect_uri 回调地址
* @param appid 账号
* @param state 状态
* @return
*/
public static void getAccessCodeRuquest(String appid,String redirect_uri,String state) {
String redirect_urito="";
try {
redirect_urito=URLEncoder.encode(redirect_uri,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String requestUrl=getAccessCodeURL(appid,redirect_urito,state);
HttpUtil.httpRequestUrl(requestUrl, "GET"); // Http GET请求
// 如果请求成功
}
}
package hls.plugin.weixin.fuwu;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import hls.plugin.weixin.qiye.DBUtil;
import net.sf.json.JSONObject;
public class sendPostForOpenid {
private String urlTemplate = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
private String msgUrlTemplate = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={accessToken}";
private int MAX_RETRY = 3;
public String httpRequestUrl(String requestUrl, String method) throws IOException {
HttpClient client = new HttpClient();
HttpMethod httpMethod = null;
String openId = "";
if ("GET".equals(method)) {
httpMethod = new GetMethod(requestUrl);
} else {
httpMethod = new PostMethod(requestUrl);
try {
} catch (Exception e) {
e.printStackTrace();
}
}
try {
client.executeMethod(httpMethod);
openId = httpMethod.getResponseHeader("openid").getValue();
httpMethod.releaseConnection();
} catch (HttpException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (httpMethod != null) {
httpMethod.releaseConnection();
}
}
return openId;
}
public String getOpenId(String url) {
String openId = null;
String requestUrl = url;
try {
openId = httpRequestUrl(requestUrl, "GET");
} catch (IOException e) {
e.printStackTrace();
}
return openId;
}
public String replyText2OpenId(String appid,String secret,String toOpenId, String msgType, String msg) throws IllegalArgumentException {
String result = "failed";
try{
String accessToken = getAccessToken(appid,secret);
if (isNullOrEmpty(toOpenId) || isNullOrEmpty(msg) || isNullOrEmpty(msgType)) {
StringBuffer errorInfo = new StringBuffer("toOpenId:");
errorInfo.append(String.valueOf(toOpenId));
errorInfo.append("\tmsgType:");
errorInfo.append(String.valueOf(msgType));
errorInfo.append("\tmsg:");
errorInfo.append(String.valueOf(msg));
throw new IllegalArgumentException(errorInfo.toString());
}
String msgUrl = msgUrlTemplate.replace("{accessToken}", accessToken);
String jsonString = "{\"touser\":\""+toOpenId+"\",\"msgtype\":\""+msgType+"\",\"text\":{\"content\":\""+msg+"\"}}";
sendMsg(msgUrl, jsonString);
result = "success";
}catch(Exception e){
e.printStackTrace();
}
return result;
}
public String replyText2OpenIds(String appid,String secret,String[] toOpenId, String msgType) throws IllegalArgumentException {
String result = "failed";
try{
String accessToken = getAccessToken(appid,secret);
String msgUrl = msgUrlTemplate.replace("{accessToken}", accessToken);
for(int i=0; i<toOpenId.length; i++){
JSONObject jsonObject = JSONObject.fromObject(toOpenId[i]);
String openid = jsonObject.get("openid").toString();
String msg = jsonObject.get("msg").toString();
String jsonString = "{\"touser\":\""+openid+"\",\"msgtype\":\""+msgType+"\",\"text\":{\"content\":\""+msg+"\"}}";
sendMsg(msgUrl, jsonString);
}
result = "success";
}catch(Exception e){
e.printStackTrace();
}
return result;
}
private boolean isNullOrEmpty(String s) {
if (s == null || s.length() < 1) {
return true;
}
return false;
}
public String getAccessToken(String appid,String secret) throws IllegalArgumentException, Exception {
String accessToken = null;
HttpClient client = new HttpClient();
// 从数据库获取access_token
Connection connection = DBUtil.getConnection();
String sql = "select access_token from wfl_access_token where expire_date > ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setDate(1, new Date(System.currentTimeMillis()));
ResultSet resultSet = pstmt.executeQuery();
// 如果存在,则使用数据库的access_token
if (resultSet.next()) {
accessToken = resultSet.getString(1);
} else {
// 像服务器请求
if (isNullOrEmpty(appid) || isNullOrEmpty(secret)) {
throw new IllegalArgumentException("cannot get access token");
}
String url = urlTemplate.replace("{appid}", appid).replace("{secret}", secret);
GetMethod get = new GetMethod(url);
int flag = 1;
while (flag > 0) {
int executeMethod = client.executeMethod(get);
byte[] responseBody = get.getResponseBody();
JSONObject jsonObject = JSONObject.fromObject(new String(responseBody));
Object object = jsonObject.get("access_token");
if (object == null) {
System.err.println("get token failed, try again!");
flag++;
if (flag > MAX_RETRY) {
flag = -1;
throw new Exception("get token failed max times. stopped!");
}
} else {
Object expire = jsonObject.get("expires_in");
accessToken = String.valueOf(object);
sql = "insert into wfl_access_token(access_token,expire_date,creation_date,created_by,last_update_date,last_updated_by) values('"
+accessToken
+"',sysdate+"
+String.valueOf(expire)
+"/24/60/60,sysdate,'1',sysdate,'1')";
Statement stmt = connection.createStatement();
// 保存到数据库
stmt.execute(sql);
flag = -1;
}
}
}
pstmt.close();
connection.commit();
connection.close();
return accessToken;
}
private void sendMsg(String url,String msg) throws Exception{
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
RequestEntity requestEntity = new StringRequestEntity(msg,"text/xml","UTF-8");
postMethod.setRequestEntity(requestEntity);
int executeMethod = client.executeMethod(postMethod);
}
public static void main(String[] args) throws Exception{
sendPostForOpenid sendPostForOpenid = new sendPostForOpenid();
/*String accessToken = sendPostForOpenid.getAccessToken("wx114d72be121c0797", "f6490d5f2c58656be86fd522837db943 ");
System.out.println(accessToken);*/
String[] aStrings= new String[]{};
sendPostForOpenid.replyText2OpenIds("wx114d72be121c0797", "f6490d5f2c58656be86fd522837db943", new String[]{"{'openid':'oTZ5RwCyG8mUOgf_1bX4J9nY2L-4','msg':'345'}","{'openid':'12314-4','msg':'abc'}"}, "text");
}
}
package hls.plugin.weixin.qiye;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
* @title DBUtil
* @Description:
* @Company:
* @author jianwen_zheng
* @date 2016-10-9
*/
public class DBUtil {
private static String oracleDriver;
private static String url;
private static String username;
private static String password;
static {
try {
get();
Class.forName(oracleDriver);
} catch (ClassNotFoundException e) {
System.out.println("驱动包不存在..");
}
}
/**
*
*/
public DBUtil() {
}
public InputStream getPathName(String pathName) {
return DBUtil.class.getClassLoader().getResourceAsStream(pathName);// "com/wx/util/data_jdbc.properties"
}
private static void get() {
Properties prop = new Properties();
InputStream in = null;
try {
in = new DBUtil().getPathName("hls/plugin/weixin/qiye/data_jdbc.properties");
prop.load(in); // /加载属性列表
oracleDriver = prop.getProperty("oracleDriver");
url = prop.getProperty("url");
username = prop.getProperty("username");
password = prop.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取数据连接
*
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
public static void main(String[] args) {
try {
// DBUtil.get();
DBUtil.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package hls.plugin.weixin.qiye;
public class Ertrt {
/**
* @param args
*/
public static void main(String[] args) {
String time=(long)(Math.random()*10000000)+"";
System.out.println(time);
}
}
package hls.plugin.weixin.qiye;
/**
* @title FndAtmAttachment
* @Description:
* @Company:
* @author jianwen_zheng
* @date 2016-10-12
*/
public class FndAtmAttachment {
private String source_pk_value;
private String file_type_code;
private String mime_type;
private String file_name;
private int file_size;
private String file_path;
private int user_id;
private String table_name;
private String table_pk_value;
/**
*
*/
public FndAtmAttachment() {
}
/**
* @param source_pk_value
* @param file_type_code
* @param mime_type
* @param file_name
* @param file_size
* @param file_path
* @param user_id
* @param table_name
* @param table_pk_value
*/
public FndAtmAttachment(String source_pk_value, String file_type_code,
String mime_type, String file_name, int file_size,
String file_path, int user_id, String table_name,
String table_pk_value) {
super();
this.source_pk_value = source_pk_value;
this.file_type_code = file_type_code;
this.mime_type = mime_type;
this.file_name = file_name;
this.file_size = file_size;
this.file_path = file_path;
this.user_id = user_id;
this.table_name = table_name;
this.table_pk_value = table_pk_value;
}
public String getSource_pk_value() {
return source_pk_value;
}
public void setSource_pk_value(String source_pk_value) {
this.source_pk_value = source_pk_value;
}
public String getFile_type_code() {
return file_type_code;
}
public void setFile_type_code(String file_type_code) {
this.file_type_code = file_type_code;
}
public String getMime_type() {
return mime_type;
}
public void setMime_type(String mime_type) {
this.mime_type = mime_type;
}
public String getFile_name() {
return file_name;
}
public void setFile_name(String file_name) {
this.file_name = file_name;
}
public int getFile_size() {
return file_size;
}
public void setFile_size(int file_size) {
this.file_size = file_size;
}
public String getFile_path() {
return file_path;
}
public void setFile_path(String file_path) {
this.file_path = file_path;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getTable_name() {
return table_name;
}
public void setTable_name(String table_name) {
this.table_name = table_name;
}
public String getTable_pk_value() {
return table_pk_value;
}
public void setTable_pk_value(String table_pk_value) {
this.table_pk_value = table_pk_value;
}
}
package hls.plugin.weixin.qiye;
/**
* @title IWeChat
* @Description: ݲҽӿ
* @Company:
* @author jianwen_zheng
* @date 2016-10-9
*/
public interface IWeChatDao {
/**
*
* @return
*/
public boolean save(FndAtmAttachment fnd);
}
package hls.plugin.weixin.qiye;
import hls.plugin.weixin.common.GetPropertiesValue;
import hls.plugin.weixin.common.HttpUtil;
public class RequestToCompany {
public static void sendMassage(String [] mediaId,String table_pk_value,String userId,String tableName,String pck_id) {
GetPropertiesValue gp=new GetPropertiesValue();
for (int i = 0; i < mediaId.length; i++) {
String requestUrl=gp.GetValue().get("weixinserviceUrl")+"?mediaId="+mediaId[i]+"&pck_id="+pck_id+"&userId="+userId+"&tableName="+tableName+"&table_pk_value="+table_pk_value;
HttpUtil.httpRequestUrl(requestUrl, "GET"); // Http GET
}
}
public static void main(String[] args) {
// String a[]={"1qyU7RGN3LHdsMrqCw7VrTc85wY-Q5Z3pEk_VJKcU9E3Nx_ukMH7ik2Vp_43EiMa6VyEjpNwtuEQ2ILqoe7F5cA"};
}
}
package hls.plugin.weixin.qiye;
import hls.plugin.weixin.common.HttpUtil;
import java.util.Map;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class WXupAndDown {
/**
* 获得token
* @param acceToken_urlx 请求的url
* @return
*/
public static String getJSSDKAccessToken(String acceToken_urlx) {
String returnString = "";
String requestUrl = acceToken_urlx;
JSONObject jsonObject = JSONObject.fromObject(HttpUtil.httpRequestUrl(
requestUrl, "GET")); // Http GET请求
// 如果请求成功
if (null != jsonObject) {
try {
returnString = jsonObject.getString("access_token");
} catch (JSONException e) {
returnString = null;
}
}
return returnString;
}
/**
* 获得ticket
* @param access_token 上面来的token
* @param ticket_urlx ticket的请求地址
* @return
*/
public static String getJSSDKTicket(String access_token, String ticket_urlx) {
String returnString = "";
String requestUrl = ticket_urlx.replace("ACCESS_TOKEN", access_token);
JSONObject jsonObject = JSONObject.fromObject(HttpUtil.httpRequestUrl(
requestUrl, "GET"));
// 如果请求成功
if (null != jsonObject) {
try {
returnString = jsonObject.getString("ticket");
} catch (JSONException e) {
returnString = null;
}
}
return returnString;
}
/**
* 获得签名
* @param id 账号
* @param secrect 密码
* @param url 返回地址
* @return
*/
public static Map<String, String> getSignture(String id, String secrect,
String url) {
String acceToken_urlx="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+id+"&corpsecret="+secrect;
String ticket_urlx="https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=ACCESS_TOKEN";
String js_accessToken = WXupAndDown.getJSSDKAccessToken(acceToken_urlx); // 获取微信jssdk---access_token
String jsapi_ticket = WXupAndDown.getJSSDKTicket(js_accessToken,ticket_urlx); // 获取微信jssdk---ticket
// System.out.println("jsapi_ticket==="+jsapi_ticket);
Map<String, String> map = WxJSsign.sign(jsapi_ticket, url);
return map;
}
public static void main(String[] args) {
String id ="wx4257809fde0f5986";
String secrect="iTgSpAaEYejcyPBLlyikzx6kvSVuiMBxotfAkAdWAKo6nF8cefdJSTgLXqivXpZ7";
String url="http://cmsplus.com.cn";
Map<String, String> map = getSignture(id,secrect,url);
System.out.println("1"+map.get("nonceStr"));
System.out.println("2"+map.get("timestamp"));
System.out.println("3"+map.get("signature"));
}
}
\ No newline at end of file
package hls.plugin.weixin.qiye;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
/**
* @title WeCatDaoImpl
* @Description:
* @Company:
* @author jianwen_zheng
* @date 2016-10-12
*/
public class WeCatDaoImpl implements IWeChatDao {
public static void main(String[] args) {
FndAtmAttachment fnd = new FndAtmAttachment("1","1","1","1",1,"1",1,"1","1");
boolean ss =new WeCatDaoImpl().save(fnd);
System.out.println(ss);
}
public boolean save(FndAtmAttachment fnd) {
boolean success = false;
Connection conn = null;
CallableStatement pst = null;
try {
conn = DBUtil.getConnection();
pst = conn.
prepareCall("{ call fnd_atm_attachment_all_pkg.insert_fnd_atm_attachment(?,?,?,?,?,?,?,?,?,?) }");
pst.registerOutParameter(1, Types.INTEGER);
pst.setString(2, fnd.getSource_pk_value());
pst.setString(3, fnd.getFile_type_code());
pst.setString(4, fnd.getMime_type());
pst.setString(5, fnd.getFile_name());
pst.setInt(6, fnd.getFile_size());
pst.setString(7, fnd.getFile_path());
pst.setInt(8, fnd.getUser_id());
pst.setString(9, fnd.getTable_name());
pst.setString(10, fnd.getTable_pk_value());
pst.execute();
conn.commit();
success = true;
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (null != pst)
pst.close();
if (null != conn)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return success;
}
}
package hls.plugin.weixin.qiye;
import hls.plugin.weixin.common.GetPropertiesValue;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeiImagePostTo {
/**
* 上传到微信服务器
*
* @param fileType
* 文件类型
* @param filePath
* 本地上传文件路径
* @param id
* 账号
* @param secret
* 密码
* @return
* @throws Exception
*/
public void send(String mediaId, String pck_id, String fileName,String filetype, String fileSize,String userId,String tableName,String table_pk_value) {
GetPropertiesValue gp = new GetPropertiesValue();
HttpURLConnection con = null;
OutputStream out = null;
InputStream in = null;
InputStream inputStream = null;
ByteArrayOutputStream baos = null;
int length = 0;
try {
File file = new File(gp.GetValue().get("winXinSavePath") + "/"
+ fileName + "." + filetype);
if (!file.exists() || !file.isFile()) {
throw new IOException("文件不存在");
}
/**
* 第一部分
*/
String enCodemediaId = mediaId;
URL urlObj = new URL(gp.GetValue().get("zuLinserviceUrl")
+ "?mediaId=" + enCodemediaId + "&pck_id=" + pck_id
+ "&fileName=" + fileName + "&filetype=" + filetype
+ "&fileSize=" + fileSize+"&userId="+userId+"&tableName="+tableName+"&table_pk_value="+table_pk_value);
con = (HttpURLConnection) urlObj.openConnection();
// con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Content-Length",fileSize);
con.setRequestProperty("Content-type", "application/image");//这句相当重要,没有回报各种错
con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
//con.setUseCaches(false); // post方式不能使用缓存
con.connect();
// 获得输出流
out = con.getOutputStream();
in = new FileInputStream(file);
int bytes=-1;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
inputStream = con.getInputStream();
// temp.close();
} catch (Exception e) {
System.out.println("传输异常:" + e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (con != null) {
con.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}// 再读取一遍
}
}
}
}
package hls.plugin.weixin.qiye;
import hls.plugin.weixin.common.HttpUtil;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class WeiImageUpload {
/**
* 上传到微信服务器
* @param fileType 文件类型
* @param filePath 本地上传文件路径
* @param id 账号
* @param secret 密码
* @return
* @throws Exception
*/
public JSONObject send(String fileType, String filePath,String id,String secret) throws Exception {
String result = null;
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
throw new IOException("文件不存在");
}
String token=getNowToken(id,secret);
/**
* 第一部分
*/
URL urlObj = new URL("https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token="+ token
+ "&type="+fileType+"");
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用缓存
// 设置请求头信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filename=\""+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream out = new DataOutputStream(con.getOutputStream());
// 输出表头
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 结尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
try {
// 定义BufferedReader输入流来读取URL的响应
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
//System.out.println(line);
buffer.append(line);
}
if(result==null){
result = buffer.toString();
}
} catch (IOException e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
throw new IOException("数据读取异常");
} finally {
if(reader!=null){
reader.close();
}
}
JSONObject jsonObj =JSONObject.fromObject(result);
System.out.println("jsonObj>>>>"+jsonObj);
return jsonObj;
}
public static String getNowToken(String id,String secret) {
String returnString = "";
String requestUrl=getNowTokenURL(id,secret);
JSONObject jsonObject = JSONObject.fromObject(HttpUtil.httpRequestUrl(
requestUrl, "GET")); // Http GET请求
// 如果请求成功
if (null != jsonObject) {
try {
returnString = jsonObject.getString("access_token");
} catch (JSONException e) {
returnString = null;
}
}
return returnString;
}
public static String getNowTokenURL(String id,String secret){
String mutiurl="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+id+"&corpsecret="+secret;
return mutiurl;
}
public static void main(String[] args) {
try {
JSONObject jsonObj=new WeiImageUpload().send("image","C:/Users/Administrator/Desktop/pak/3.jpg","wx4257809fde0f5986","iTgSpAaEYejcyPBLlyikzx6kvSVuiMBxotfAkAdWAKo6nF8cefdJSTgLXqivXpZ7");
System.out.println(jsonObj.getString("media_id"));
System.out.println(jsonObj.getString("created_at"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static Map<String, String> weiUpload(String fileType, String filePath,String id,String secret){
Map<String, String> map=new HashMap<String, String>();
try {
JSONObject jsonObj=new WeiImageUpload().send(fileType,filePath,id,secret);
map.put("media_id", jsonObj.getString("media_id"));
map.put("created_at", jsonObj.getString("created_at"));
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
package hls.plugin.weixin.qiye;
import hls.plugin.weixin.common.HttpUtil;
import java.awt.RadialGradientPaint;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class WeixinDownload {
static WeixinDownload weixinMedia = null;
/**
* 下载媒体文件:
* 获取媒体文件
* @param accessToken 接口访问凭证
* @param media_id 媒体文件id
* @param savePath 文件在服务器上的存储路径
* */
public static String downloadMedia(String accessToken, String mediaId, String savePath,String imageName) {
String filePath = null;
// 拼接请求地址
String filetype="";
HttpURLConnection conn=null;
BufferedInputStream bis=null;
FileOutputStream fos=null;
String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
try {
URL url = new URL(requestUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
if (!savePath.endsWith("/")) {
savePath += "/";
}
// 根据内容类型获取扩展名
String fileExt = WeixinUtil.getTypeByStream(conn.getHeaderField("Content-Type"));
// 将mediaId作为文件名
filePath = savePath + imageName +"."+fileExt.substring(fileExt.indexOf("/")+1);
filetype=fileExt.substring(fileExt.indexOf("/")+1);
bis = new BufferedInputStream(conn.getInputStream());
fos = new FileOutputStream(new File(filePath));
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1)
fos.write(buf, 0, size);
} catch (Exception e) {
filePath = null;
String error = String.format("下载媒体文件失败:%s", e);
System.out.println(error);
} finally{
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(conn!=null){
conn.disconnect();
}
}
return filetype;
}
public static String getNowToken(String id,String secret) {
String returnString = "";
String requestUrl=getNowTokenURL(id,secret);
JSONObject jsonObject = JSONObject.fromObject(HttpUtil.httpRequestUrl(
requestUrl, "GET")); // Http GET请求
// 如果请求成功
if (null != jsonObject) {
try {
returnString = jsonObject.getString("access_token");
} catch (JSONException e) {
returnString = null;
}
}
return returnString;
}
public static String getNowTokenURL(String id,String secret){
String mutiurl="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+id+"&corpsecret="+secret;
return mutiurl;
}
public static void main(String[] args) {
weiDownload("wx4257809fde0f5986","iTgSpAaEYejcyPBLlyikzx6kvSVuiMBxotfAkAdWAKo6nF8cefdJSTgLXqivXpZ7","1qyU7RGN3LHdsMrqCw7VrTc85wY-Q5Z3pEk_VJKcU9E3Nx_ukMH7ik2Vp_43EiMa6VyEjpNwtuEQ2ILqoe7F5cA","G:/pad/");
}
private static String createImageName() {
return (long)(Math.random()*10000000)+"";
// return Long.toString(System.currentTimeMillis() / 1000);
}
public static Map<String, String> weiDownload(String id,String secret, String mediaId, String savePath){
Map<String, String> map=new HashMap<String, String>();
String accessToken=getNowToken(id,secret);
String imageName=createImageName();
String filetype=downloadMedia(accessToken,mediaId,savePath,imageName);
String fileSize=getFileSize(savePath,imageName,filetype)+"";
map.put("fileName", imageName);
map.put("filetype", filetype);
map.put("fileSize", fileSize);
return map;
}
public static long getFileSize(String savePath,String imageName,String filetype){
long fileSize=0;
File file=new File(savePath+"/"+imageName+"."+filetype);
if (file.exists() && file.isFile()){
fileSize=file.length()/1024;
}
return fileSize;
}
}
package hls.plugin.weixin.qiye;
import hls.plugin.weixin.common.GetPropertiesValue;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class WeixinServlet extends HttpServlet {
@SuppressWarnings("static-access")
/**
* 获得mediaId进行下载到自己微信服务器,
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
GetPropertiesValue gp=new GetPropertiesValue();
String mediaId=request.getParameter("mediaId");
String pck_id=request.getParameter("pck_id");
String id=gp.GetValue().get("appid");
String secret=gp.GetValue().get("secret");
String winXinSavePath=gp.GetValue().get("winXinSavePath");
String userId=request.getParameter("userId");
String tableName=request.getParameter("tableName");
String table_pk_value=request.getParameter("table_pk_value");
//下载
Map<String,String> map=new WeixinDownload().weiDownload(id,secret,mediaId,winXinSavePath);
String fileName=map.get("fileName");
String filetype=map.get("filetype");
String fileSize=map.get("fileSize");
try {
new WeiImagePostTo().send(mediaId, pck_id, fileName, filetype, fileSize,userId,tableName,table_pk_value);
} catch (Exception e) {
e.printStackTrace();
}
//回执
PrintWriter pw = response.getWriter();
pw.println("OK!!");
pw.flush();
pw.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package hls.plugin.weixin.qiye;
public class WeixinUtil {
public static String getTypeByStream(String cot){
String type = cot.toUpperCase();
if(type.contains("FFD8FF")){
return "jpg";
}else if(type.contains("89504E47")){
return "png";
}else if(type.contains("47494638")){
return "gif";
}else if(type.contains("49492A00")){
return "tif";
}else if(type.contains("424D")){
return "bmp";
}
return type.toLowerCase();
}
}
package hls.plugin.weixin.qiye;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class WxJSsign {
public static Map<String, String> sign(String jsapi_ticket,String url){
Map<String, String> ret = new HashMap<String, String>();
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
String string1;
String signature = "";
// 注意这里参数名必须全部小写,且必须有序
string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + 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();
}
ret.put("url", url);
ret.put("jsapi_ticket", jsapi_ticket);
ret.put("nonceStr", nonce_str);
ret.put("timestamp", timestamp);
ret.put("signature", signature);
return ret;
}
private static String create_nonce_str() {
return UUID.randomUUID().toString();
}
private static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
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;
}
}
package hls.plugin.weixin.qiye;
import hls.plugin.weixin.common.GetPropertiesValue;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class ZuLinServlet extends HttpServlet {
@SuppressWarnings("static-access")
/**
* 获得mediaId进行下载,并且保存参数到数据库
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//request.setCharacterEncoding("utf-8");
InputStream in=null;
OutputStream out=null;
GetPropertiesValue gp = new GetPropertiesValue();
//String mediaId = request.getParameter("mediaId");
String pck_id = request.getParameter("pck_id");
String file_name = request.getParameter("fileName");
String mime_type = request.getParameter("filetype");
String file_size = request.getParameter("fileSize");
String userId = request.getParameter("userId");
int userId2 = Integer.parseInt(userId);
String tableName = request.getParameter("tableName");
String table_pk_value = request.getParameter("table_pk_value");
int file_size_int = Integer.parseInt(file_size);
String file_type_code =gp.GetValue().get("file_type_code");
System.out.println("file_type_code>>"+file_type_code);
System.out.println("file_size_int>>"+file_size_int);
System.out.println("table_pk_value>>"+table_pk_value);
System.out.println("tableName>>"+tableName);
System.out.println("file_size>>"+file_size);
System.out.println("mime_type>>"+mime_type);
System.out.println("file_name>>"+file_name);
String filepath = gp.GetValue().get(
"zuLinsavePath")
+ "/" + file_name+"."+mime_type;
System.out.println("filepath>>>"+filepath);
try {
in =request.getInputStream();
out = new FileOutputStream(filepath);
int bytes = -1;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(in!=null){
in.close();
}
if(out!=null){
out.flush();
out.close();
}
}
// 保存数据到数据库
FndAtmAttachment fnd = new FndAtmAttachment(table_pk_value,file_type_code,mime_type,file_name,file_size_int,filepath,userId2,tableName,pck_id);
boolean ss =new WeCatDaoImpl().save(fnd);
System.out.println(ss);
}
}
oracleDriver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@10.0.36.97:1521:hls
# url=jdbc:oracle:thin:@172.20.0.115:1521:hls
username=hls_standard
password=hls_standard
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment