首页 > 程序开发 > 移动开发 > 其他 >

通过Http地址返回JSON数据,进行解析;通过ftp返回.txt文件数据,进行解析

2016-11-08

通过Http地址返回JSON数据,进行解析;通过ftp返回 txt文件数据,进行解析。

一、通过Http地址返回JSON数据,进行解析;

package com.*.zqx.szybzx.ybzxdutytask.trigger.condi.other;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings("all")
public class AutoCcavSmsCondi implements ConditionInterface {
	
	private final static Logger LOGGER = Logger.getLogger(AutoCcavSmsCondi.class);
	
	@Autowired
	private Dao dao;
	@Autowired
//	private YbzxService ybzxService;
	private YbzxTwoService ybzxTwoService;

	@Override
	public SysTriggerCondiData condition(SysTriggerParaData entity,
			SystriggerTrigger trigger) throws Exception {
		SysTriggerCondiData stcd = new SysTriggerCondiData();	
		try {
			Map params = new HashMap();
			String urlString = "http://10.15.9.4:8010/jsp/sis/zyneJson.jsp";
			String xml = HttpXmlClient.post(urlString, params);
			xml="{'zy':[{'ddatetime':'2016-05-27 08:51:00','msg':'南海热带低压最新信息:南海热带低压的中心今天(27日)上午8点钟位于广东阳江以南大约210公里的南海北部海面上,北纬20.0度、东经112.2度,7级(14米/秒),1000百帕。预计,低压中心将以每小时20公里左右的速度向北偏西方向移动,强度变化不大,将于今天下午在广东吴川到台山一带沿海登陆,登陆后强度逐渐减弱。【中央气象台】'},{'ddatetime':'2016-05-27 08:47:00','msg':'南海热带低压最新信息:南海热带低压的中心今天(27日)上午8点钟位于广东阳江以南大约210公里的南海北部海面上,北纬20.0度、东经112.2度,7级(14米/秒),1000百帕。预计,低压中心将以每小时20公里左右的速度向北偏西方向移动,强度变化不大,将于今天下午在广东吴川到台山一带沿海登陆,登陆后强度逐渐减弱。【中央气象台】'},{'ddatetime':'2016-05-27 06:41:00','msg':'南海热带低压最新信息:南海热带低压的中心今天(27日)上午8点钟位于广东阳江以南大约210公里的南海北部海面上,北纬20.0度、东经112.2度,7级(14米/秒),1000百帕。预计,低压中心将以每小时20公里左右的速度向北偏西方向移动,强度变化不大,将于今天下午在广东吴川到台山一带沿海登陆,登陆后强度逐渐减弱。【中央气象台】'},{'ddatetime':'2016-05-27 06:34:00','msg':'南海热带低压最新信息:南海热带低压的中心今天(27日)上午8点钟位于广东阳江以南大约210公里的南海北部海面上,北纬20.0度、东经112.2度,7级(14米/秒),1000百帕。预计,低压中心将以每小时20公里左右的速度向北偏西方向移动,强度变化不大,将于今天下午在广东吴川到台山一带沿海登陆,登陆后强度逐渐减弱。【中央气象台】'}],'st':[{'ddatetime':'2016-05-27 06:34:00','msg':'南海热带低压最新信息:南海热带低压的中心今天(27日)上午8点钟位于广东阳江以南大约210公里的南海北部海面上,北纬20.0度、东经112.2度,7级(14米/秒),1000百帕。预计,低压中心将以每小时20公里左右的速度向北偏西方向移动,强度变化不大,将于今天下午在广东吴川到台山一带沿海登陆,登陆后强度逐渐减弱。【省台】'}]}";
			JSONObject jsonobj=JSONObject.fromObject(xml);//将字符串转化成json对象 
			 JSONArray zyarray = jsonobj.getJSONArray("zy");
			 JSONArray starray = jsonobj.getJSONArray("st");
			 List> zyList = (List)zyarray;
			 List> stList = (List)starray;
			 List> parameter = new ArrayList>();
			 if ( zyList!=null && zyList.size() > 0) {
				 for(Map zymap :zyList){
					 String ddatetime = zymap.get("ddatetime") ==null ? "" : zymap.get("ddatetime").toString();
					 String msg = zymap.get("msg") ==null ? "" : zymap.get("msg").toString();
					 HashMap p = new HashMap();
					 p.put("短信@all_para@",ddatetime.concat("短信"));
					 p.put("@remark@", ddatetime.concat(msg));
					 parameter.add(p);
				 }
			}
			 if ( stList!=null && stList.size() > 0) {
				 for(Map stmap :stList){
					 String ddatetime = stmap.get("ddatetime") ==null ? "" : stmap.get("ddatetime").toString();
					 String msg = stmap.get("msg") ==null ? "" : stmap.get("msg").toString();
					 HashMap p = new HashMap();
					 p.put("短信@all_para@",ddatetime.concat("短信"));
					 p.put("@remark@", ddatetime.concat(msg));
					 parameter.add(p);
				 }
			 }
			 if (parameter.size() > 0) {
				 Map obj = new HashMap();
				 obj.put("parameter", parameter);
				 obj.put("trigger", trigger);
				 stcd.setData(obj);
			}
			
		} catch (Exception e) {
			LOGGER.error("",e);
			throw e;
		}finally{
			return stcd;
		}
	}
}

HttpXmlClient.java中:

package com.*.uitl;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;


public class HttpXmlClient {
	private static Logger log = Logger.getLogger(HttpXmlClient.class);
	
	public static String post(String url, Map params) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		String body = null;
		
		log.info("create httppost:" + url);
		HttpPost post = postForm(url, params);
		
		body = invoke(httpclient, post);
		
		httpclient.getConnectionManager().shutdown();
		
		return body;
	}
二、通过ftp返回.txt文件数据,进行解析;
	String filename = "短信".concat(time).concat(".txt");
	ReadFTPFile read = new ReadFTPFile();  
        hbContents = read.readConfigFileForFTP("s01", "11", "/home/", "10.13.13.16", 1, filename);  
        if (!hbContents.contains("空气质量指数")) {
           hbContents = read.readConfigFileForFTP2("s01", "11", "/home/", "10.13.13.16", 1, filename);
	   System.out.println(hbContents);
	}
在ReadFTPFile.java中:

package com.*.ftp;


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;


public class ReadFTPFile {
	private Logger logger = Logger.getLogger(ReadFTPFile.class);

	/**
	 * 去 服务器的FTP路径下上读取文件
	 * 
	 * @param ftpUserName
	 * @param ftpPassword
	 * @param ftpPath
	 * @param FTPServer
	 * @return
	 */
	public String readConfigFileForFTP(String ftpUserName, String ftpPassword,
			String ftpPath, String ftpHost, int ftpPort, String fileName) {
		StringBuffer resultBuffer = new StringBuffer();
		FileInputStream inFile = null;
		InputStream in = null;
		FTPClient ftpClient = null;
		logger.info("开始读取绝对路径" + ftpPath + "文件!");
		try {
			ftpClient = FTPUtil.getFTPClient(ftpHost, ftpPassword, ftpUserName,
					ftpPort);
			//ftpClient.setControlEncoding("UTF-8"); // 中文支持 
//			ftpClient.setControlEncoding("GBK");  
//			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);  
//			conf.setServerLanguageCode("zh"); 
//			ftpClient.configure(conf);
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			ftpClient.changeWorkingDirectory(ftpPath);
			System.out.println("path===========:" + ftpClient.changeWorkingDirectory(ftpPath));  
			in = ftpClient.retrieveFileStream(new String(fileName.getBytes("GBK"),"iso-8859-1"));
		} catch (FileNotFoundException e) {
			logger.error("没有找到" + ftpPath + "文件");
			e.printStackTrace();
			return "暂无数据";
		} catch (SocketException e) {
			logger.error("连接FTP失败.");
			e.printStackTrace();
			return "文件读取错误,连接FTP失败.";
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("文件读取错误。");
			e.printStackTrace();
			return "暂无数据";
		}
		if (in != null) {
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(in,"utf-8"));
				String data = null;
				while ((data = br.readLine()) != null) {
					resultBuffer.append(data + "\n");
				}
			} catch (IOException e) {
				logger.error("文件读取错误。");
				e.printStackTrace();
				return "文件读取失败,请联系管理员.";
			}finally{
				try {
					ftpClient.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}else{
			logger.error("in为空,不能读取。");
			return "暂无数据";
		}
		return resultBuffer.toString();
	}
	
	public String readConfigFileForFTP2(String ftpUserName, String ftpPassword,
			String ftpPath, String ftpHost, int ftpPort, String fileName) {
		StringBuffer resultBuffer = new StringBuffer();
		InputStream in = null;
		FTPClient ftpClient = null;
		logger.info("开始读取绝对路径" + ftpPath + "文件!");
		try {
			ftpClient = FTPUtil.getFTPClient(ftpHost, ftpPassword, ftpUserName,
					ftpPort);
			//ftpClient.setControlEncoding("UTF-8"); // 中文支持 
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			ftpClient.changeWorkingDirectory(ftpPath);
			System.out.println("path===========:" + ftpClient.changeWorkingDirectory(ftpPath));  
			in = ftpClient.retrieveFileStream(new String(fileName.getBytes("GBK"),"iso-8859-1"));
		} catch (FileNotFoundException e) {
			logger.error("没有找到" + ftpPath + "文件");
			e.printStackTrace();
			return "暂无数据";
		} catch (SocketException e) {
			logger.error("连接FTP失败.");
			e.printStackTrace();
			return "文件读取错误,连接FTP失败.";
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("文件读取错误。");
			e.printStackTrace();
			return "暂无数据";
		}
		if (in != null) {
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(in,"gbk"));
				String data = null;
				while ((data = br.readLine()) != null) {
					resultBuffer.append(data + "\n");
				}
			} catch (IOException e) {
				logger.error("文件读取错误。");
				e.printStackTrace();
				return "文件读取失败,请联系管理员.";
			}finally{
				try {
					ftpClient.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}else{
			logger.error("in为空,不能读取。");
			return "暂无数据";
		}
		return resultBuffer.toString();
	}
	
	
}
相关文章
最新文章
热点推荐