向远程地址发送xml文件

public class Utils {
private static String scHtmlPath = ConfigUtil.getInstance().getConfigStr("scHtmlPath");//生成静态页面物理路径
private static String scHtmlSrc = ConfigUtil.getInstance().getConfigStr("scHtmlSrc");//外网访问静态页面路径
private static String scImgSrc = ConfigUtil.getInstance().getConfigStr("scImgSrc");//外网访问图片路径

public static String send(String url, File file,String fileName) throws IOException {
String result = null;
//File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
throw new IOException("文件不存在");
}
/**
* 第一部分
*/
URL urlObj = new URL(url);
// 连接
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=\"file\";filename=\""
+ fileName + "\"\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("1");
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();
}
}
return result;
}

/**
* Title: templateToHtmlByURL
* Description:生成静态页面
* @param @param u 模板存放路径
* @param @param filePath 文件存放路经如:x:\\abc\bbb.html
* @param @param fileName 生成静态页面名称
* @param @param detal 素材详情对象
* @param @param hostTel 主号
* @param @param localUrl 文件上传所在服务器地址
* @param @param hostName 企业号名称
* @param @return
* @return boolean
* @throws
*/
public static boolean templateToHtmlByURL(String u, String filePath,String fileName,ImSmScDetal detal,Long hostTel,String localUrl,String hostName) {
//从utl中读取html存为str
StringBuffer sb = new StringBuffer();
try
{
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.mkdirs();
}

String html = fileName+".html";

filePath += File.separator;

/*File oldFile = new File(filePath+"1396788605470.html");
if(oldFile.exists()){
oldFile.delete();
}
*/

filePath += html;

/*URL url = new URL(u);
URLConnection uc = url.openConnection();
InputStream is = uc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
while (br.ready())
{
sb.append(br.readLine() + "\n");
}
br.close();
is.close(); */

InputStream is = new FileInputStream(getRootPath()+u);//读取模块文件
BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
while (br.ready())
{
sb.append(br.readLine() + "\n");
}
is.close();
br.close();

String str = sb.toString();
String[] scArr = fileName.split("_");
if(ConfigUtil.getInstance().getConfigStr("scStaticsUrl") == null){
str = str.replace("#scStaticsUrl#", "");
}else{
str = str.replace("#scStaticsUrl#", ConfigUtil.getInstance().getConfigStr("scStaticsUrl"));
}
str = str.replaceAll("#sc_id#", scArr[0]);
str = str.replaceAll("#detal_id#",scArr[1]);
str = str.replaceAll("#host_tel#", String.valueOf(hostTel));
if(detal.getTitle() == null){
str = str.replace("#entity.title#", "");
}else{
str = str.replace("#entity.title#", detal.getTitle());
}
str = str.replaceAll("#entity.createTime#", DateUtils.dateToString(detal.getCreateTime(), DateUtils.yyyy_MM_dd));
if(hostName == null){
str = str.replace("#hostName#", "");
}else{
str = str.replace("#hostName#", hostName);
}

String imgStr = "";
if(detal.getAccessoryUrl() != null && detal.getAccessoryUrl().indexOf("http:") > -1){
str = str.replace("#entity.imgurl#",detal.getAccessoryUrl());
if(detal.getImgState() != null && detal.getImgState().longValue() != 2){
imgStr = "<img src='"+detal.getAccessoryUrl()+"' width='100%' onerror='this.parentNode.removeChild(this)' />";
}
}else{
if(detal.getAccessoryUrl() != null){
str = str.replace("#entity.imgurl#",scImgSrc + detal.getAccessoryUrl());
if(detal.getImgState() != null && detal.getImgState().longValue() != 2){
imgStr = "<img src='"+scImgSrc+detal.getAccessoryUrl()+"' width='100%' onerror='this.parentNode.removeChild(this)' />";
}
}else{
str = str.replace("#entity.imgurl#","");
}
}
str = str.replace("#entity.coverimgurl#",imgStr);

if(detal.getContent() != null){
if(scImgSrc != null){
str = str.replace("#entity.content#", detal.getContent().replace(localUrl, scImgSrc));
}else{
str = str.replace("#entity.content#", detal.getContent());
}
}

if(detal.getPvShareState() != null && detal.getPvShareState().longValue() == 1){
str = str.replaceAll("#entity.pvState#","1");
}else{
str = str.replaceAll("#entity.pvState#","2");
}

if(detal.getIsShare() != null && detal.getIsShare().longValue() == 1){
str = str.replaceAll("#entity.isShare#","1");
}else{
str = str.replaceAll("#entity.isShare#","2");
}

if(detal.getSummary() == null){
str = str.replace("#entity.desc#", "");
}else{
str = str.replace("#entity.desc#", detal.getSummary());
}

//写入文件
/*File f = new File(filePath);
BufferedWriter o = new BufferedWriter(new FileWriter(f));
o.write(str);
o.close(); */
Writer ow = new OutputStreamWriter(new FileOutputStream(filePath), "GBK");
ow.write(str);
ow.flush();
ow.close();
return true;
} catch (Exception e)
{
e.printStackTrace();
return false;
}
}

/**
* Title: thirtyTemplateToHtmlByURL
* Description: 第三方静态页面模板生成静态页面
*
* @param @param u 模板路径
* @param @param filePath 文件存放路经如:x:\\abc\bbb.html
* @param @param fileName 生成静态页面名称
* @param @param detal 素材详情
* @param @param hostTel 主号
* @param @param hostName 企业名称
* @param @return
* @return boolean
* @throws
*/
public static boolean thirtyTemplateToHtmlByURL(String u, String filePath,String fileName,ImSmScDetal detal,Long hostTel,String hostName) {
//从utl中读取html存为str
StringBuffer sb = new StringBuffer();
try
{
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.mkdirs();
}

String html = fileName+".html";

filePath += File.separator;

/*File oldFile = new File(filePath+"1396788605470.html");
if(oldFile.exists()){
oldFile.delete();
}
*/

filePath += html;
/*
URL url = new URL(u);
URLConnection uc = url.openConnection();
InputStream is = uc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
while (br.ready())
{
sb.append(br.readLine() + "\n");
}
br.close();
is.close(); */

InputStream is = new FileInputStream(getRootPath()+u);//读取模块文件
BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
while (br.ready())
{
sb.append(br.readLine() + "\n");
}
is.close();
br.close();

String str = sb.toString();
String[] scArr = fileName.split("_");
if(ConfigUtil.getInstance().getConfigStr("scStaticsUrl") == null){
str = str.replace("#scStaticsUrl#", "");
}else{
str = str.replace("#scStaticsUrl#", ConfigUtil.getInstance().getConfigStr("scStaticsUrl"));
}

str = str.replaceAll("#sc_id#", scArr[0]);
str = str.replaceAll("#detal_id#",scArr[1]);
str = str.replaceAll("#host_tel#", String.valueOf(hostTel));
if(detal.getTitle() == null){
str = str.replace("#entity.title#", "");
}else{
str = str.replace("#entity.title#", detal.getTitle());
}
if(hostName == null){
str = str.replace("#hostName#", "");
}else{
str = str.replace("#hostName#", hostName);
}
if(detal.getUrl() == null){
str = str.replace("#thirtyUrl#", "");
}else{
str = str.replace("#thirtyUrl#", detal.getUrl());
}

if(detal.getIsShare() != null && detal.getIsShare().longValue() == 1){
str = str.replaceAll("#entity.isShare#","1");
}else{
str = str.replaceAll("#entity.isShare#","2");
}

if(detal.getAccessoryUrl() != null && detal.getAccessoryUrl().indexOf("http:") > -1){
str = str.replace("#entity.imgurl#",detal.getAccessoryUrl());
}else{
if(detal.getAccessoryUrl() == null){
str = str.replace("#entity.imgurl#","");
}else{
str = str.replace("#entity.imgurl#",scImgSrc + detal.getAccessoryUrl());
}

}

if(detal.getPvShareState() != null && detal.getPvShareState().longValue() == 1){
str = str.replaceAll("#entity.pvState#","1");
}else{
str = str.replaceAll("#entity.pvState#","2");
}
if(detal.getSummary() == null){
str = str.replace("#entity.desc#", "");
}else{
str = str.replace("#entity.desc#", detal.getSummary());
}

//写入文件
/*File f = new File(filePath);
BufferedWriter o = new BufferedWriter(new FileWriter(f));
o.write(str);
o.close(); */
Writer ow = new OutputStreamWriter(new FileOutputStream(filePath), "GBK");
ow.write(str);
ow.flush();
ow.close();
return true;
} catch (Exception e)
{
e.printStackTrace();
return false;
}
}


/**
* Title: createScWebHtml
* Description:生成页面素材静态页面
* @param @param u 模板路径
* @param @param filePath 文件存放路经如:x:\\abc\bbb.html
* @param @param fileName 生成静态页面名称
* @param @param entity 页面素材对象
* @param @param localUrl 文件上传所在服务器地址
* @param @param hostName 企业名称
* @param @return
* @return boolean
* @throws
*/
public static boolean createScWebHtml(String u, String filePath,String fileName,ImSmScWeb entity,String localUrl,String hostName) {
//从utl中读取html存为str
StringBuffer sb = new StringBuffer();
try
{
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.mkdirs();
}

String html = fileName+".html";

filePath += File.separator;

/*File oldFile = new File(filePath+"1396788605470.html");
if(oldFile.exists()){
oldFile.delete();
}
*/

filePath += html;

/*URL url = new URL(u);
URLConnection uc = url.openConnection();
InputStream is = uc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
while (br.ready())
{
sb.append(br.readLine() + "\n");
}
br.close();
is.close(); */

InputStream is = new FileInputStream(getRootPath()+u);//读取模块文件
BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
while (br.ready())
{
sb.append(br.readLine() + "\n");
}
is.close();
br.close();

String str = sb.toString();

String imgStr = "";
if(entity.getImgState().equals(1l)){
if(entity.getAccessoryImg() != null && !entity.getAccessoryImg().equals("")){
if(entity.getAccessoryImg().indexOf("http:") <= -1){
imgStr = "<img src='"+scImgSrc+entity.getAccessoryImg()+"' width='100%' />";
}else{
imgStr = "<img src='"+entity.getAccessoryImg()+"' width='100%' />";
}
}
}

if(ConfigUtil.getInstance().getConfigStr("scStaticsUrl") == null){
str = str.replace("#scStaticsUrl#", "");
}else{
str = str.replace("#scStaticsUrl#", ConfigUtil.getInstance().getConfigStr("scStaticsUrl"));
}

str = str.replaceAll("#sc_id#", String.valueOf(entity.getId()));
str = str.replaceAll("#detal_id#","0");
str = str.replaceAll("#host_tel#", String.valueOf(entity.getHostTel()));
if(hostName == null){
str = str.replace("#hostName#", "");
}else{
str = str.replace("#hostName#", hostName);
}

if(entity.getAccessoryImg() != null && !entity.getAccessoryImg().equals("")){
if(entity.getAccessoryImg().indexOf("http:") <= -1){
str = str.replace("#entity.imgurl#",scImgSrc+entity.getAccessoryImg());
}else{
str = str.replace("#entity.imgurl#",entity.getAccessoryImg());
}
}else{
if(entity.getAccessoryImg() != null){
str = str.replace("#entity.imgurl#",entity.getAccessoryImg());
}else{
str = str.replace("#entity.imgurl#","");
}
}

if(entity.getPvShareState() != null && entity.getPvShareState().longValue() == 1){
str = str.replaceAll("#entity.pvState#","1");
}else{
str = str.replaceAll("#entity.pvState#","2");
}

//str = str.replaceAll("#entity.imgurl#",entity.getAccessoryImg());
if(entity.getTitle() == null){
str = str.replace("#entity.title#", "");
}else{
str = str.replace("#entity.title#", entity.getTitle());
}
if(entity.getSubTitle() == null){
str = str.replace("#entity.subTitle#", "");
}else{
str = str.replace("#entity.subTitle#", entity.getSubTitle());
}
if(entity.getAuthor() == null){
str = str.replace("#entity.author#", "");
}else{
str = str.replace("#entity.author#", "作者:"+entity.getAuthor());
}
if(entity.getNewsDate() == null){
str = str.replace("#entity.newsDate#", "");
}else{
str = str.replace("#entity.newsDate#", "日期:"+entity.getNewsDate());
}

str = str.replace("#entity.coverimgurl#",imgStr);
if(entity.getContent() != null){
if(scImgSrc != null){
str = str.replace("#entity.content#", entity.getContent().replace(localUrl, scImgSrc));
}else{
str = str.replace("#entity.content#", entity.getContent());
}

}
//写入文件
/*File f = new File(filePath);
BufferedWriter o = new BufferedWriter(new FileWriter(f));
o.write(str);
o.close(); */
Writer ow = new OutputStreamWriter(new FileOutputStream(filePath), "GBK");
ow.write(str);
ow.flush();
ow.close();
return true;
} catch (Exception e)
{
e.printStackTrace();
return false;
}
}

/**
* Title: getFileSize
* Description:获取文件大小
* @param addr
* @return String
* @throws
*/
public static String getFileSize(String addr) {
StringBuilder rtn = new StringBuilder();
OutputStream os = null;
PrintWriter pw = null;
BufferedReader in = null;
System.out.println("addr:" + addr);
try {
URL url = new URL(addr);
HttpURLConnection uc = (HttpURLConnection)url.openConnection();

uc.setConnectTimeout(2000); //连接超时设置为2s
uc.setReadTimeout(20000); //读超时设置为20s
uc.setDoOutput(true); //因为这个是post请求,参数要放在http正文内,因此需要设为true,默认情况下是false
uc.setUseCaches(false); //post请求不能使用缓存
// 设定传送的内容类型是可序列化的java对象(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
uc.setRequestProperty("Content-type", "text/xml;charset=GBK");
uc.setRequestMethod("POST"); // 设定请求的方法为"POST",默认是GET
uc.connect();

os = uc.getOutputStream();
OutputStreamWriter out = new OutputStreamWriter(os, "GBK");
pw = new PrintWriter(out);
pw.print("");
pw.flush();

/*获取服务器端返回信息*/
in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "GBK"));
String inputLine;
while((inputLine = in.readLine()) != null){
rtn.append(inputLine).append("\r\n");
}

} catch(SocketTimeoutException e) {
return "time_out";
} catch(ConnectException e) {
return "connect_exception";
}
catch (Exception ex) {
System.out.println("调用IMCC监控中心接口异常" + ex);
} finally {
try {
if (pw != null) {
pw.close();
pw = null;
}

if (os != null) {
os.close();
os = null;
}

if (in != null) {
in.close();
in = null;
}
}
catch (Exception ex) {
System.out.println("释放资源异常" + ex);
}
}
return rtn.toString();
}

public static String processImg(String path) {
String[] arr = path.split("/");
int length = arr.length;
if (isNumber(arr[length-2])) {
return arr[length-3] + "/" + arr[length-2] + "/" + arr[length-1];
}
else {
return arr[length-1];
}
}

public static String processAuthUrl(String authUrl){
if(authUrl != null && !"".equals(authUrl)){
String[] arr = authUrl.split("/");
return arr[2];
}else{
return "";
}

}

public static boolean isNumber(String str) {
try {
Long.parseLong(str);
}
catch (NumberFormatException e) {
return false;
}
return true;
}


public static String getRootPath() {
String PATH = "";
if (PATH == null || PATH.equals("")) {
PATH = Utils.class.getResource("/").getPath();
PATH = PATH.replaceAll("WEB-INF/classes/", "");
try {
PATH = URLDecoder.decode(PATH, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}

}
return PATH;
}


public static String editKeyToCmdContent(ImSmScInfo info) {
String ret = null;
if ("1".equals(info.getType()) || "2".equals(info.getType())) { //图文
ret = "<yx>news</yx>" + info.getDetail();
}
if ("3".equals(info.getType())) { //文本
ret = info.getDetail();
}
if ("4".equals(info.getType())) { //图片
String str = "";
if (info.getDetail() != null) {
String detail = info.getDetail();
int index = detail.lastIndexOf('/');
if (index != -1) {
str = processImg(info.getDetail());
}
}
ret = "<weixin><img>" + str + "</img></weixin>";
}
if ("5".equals(info.getType())) { //语音
String str = "";
if (info.getDetail() != null) {
String detail = info.getDetail();
int index = detail.lastIndexOf('/');
if (index != -1) {
str = processImg(info.getDetail());
}
}
ret = "<weixin><voice>" + str + "</voice></weixin>";
}
if ("6".equals(info.getType())) { //视频
String str = "";
if (info.getDetail() != null) {
String detail = info.getDetail();
int index = detail.lastIndexOf('/');
if (index != -1) {
str = processImg(info.getDetail());
}
}
ret = "<weixin><video>" + str + "</video></weixin>";
}
return ret;
}
}

猜你喜欢

转载自blog.csdn.net/warmlizhan/article/details/84693523