`
Asen丶
  • 浏览: 40425 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

常用工具类

阅读更多

Json工具类

package com.asen.utils.json;

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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

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

/**
 * Json工具类
 * @author Asen 2017年2月19日 下午11:03:56
 */
public class JsonUtil {

	/**
	 * 对象转换为Json
	 * @param obj 传入的对象
	 * @return
	 */
	public static String Object2Json(Object obj){
		JSONObject jsonStr = JSONObject.fromObject(obj);
		return jsonStr.toString();
	}
	
	/**
	 * 将Json转换为对应的java对象
	 * @param str 传入的Json
	 * @param clazz 需要封装的对象
	 * @return
	 */
	public static Object Json2Object(String jsonStr, Class<?> clazz){
		JSONObject obj = new JSONObject().fromObject(jsonStr);
		Object object = JSONObject.toBean(obj,clazz);
		return object;
	}
	
	/**
	 * 将Map转换为Json
	 * @param map 传入的map
	 * @return
	 */
	public static String Map2Json(Map<String, ?> map){
		ObjectMapper mapper = new ObjectMapper();
		String jsonStr = null;
		try {
			jsonStr = mapper.writeValueAsString(map);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonStr;
	}
	
	/**
	 * 将Json转换为Map
	 * @param str 传入的Json
	 * @return
	 */
	public static Map<String, Object> Json2Map(String jsonStr){
		Map<String, Object> map = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		
		try {
			map = mapper.readValue(jsonStr, new TypeReference<HashMap<String, String>>(){});
		} catch (Exception e) {
			// TODO: handle exception
		}
		return map;
	}

	/**
	 * 将List转换为Json
	 * @param list 传入的list,返回的是一个Json数组
	 * @return
	 */
	public static String List2Json(List<Object> list){
		JSONArray jsonStr = JSONArray.fromObject(list);
		return jsonStr.toString();
	}
	
	/**
	 * 将Json转换为List
	 * @param jsonStr 传入的json,需要传入一个Json数组
	 * @return
	 */
	public static List<Object> Json2List(String jsonStr){
		JSONArray array = JSONArray.fromObject(jsonStr);
		List<Object> list = JSONArray.toList(array);
		return list;
	}
}
package com.asen.utils.json;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.JSONArray;

/**
 * 网络请求带Json解析
 * @author Asen 2017年2月19日 下午11:03:34
 */
public class LoadJson {
	// 调用接口,获取Json
	private static Map<String, Object> loadJSON(String url) {
		StringBuilder json = new StringBuilder();
		try {
			URL oracle = new URL(url);
			HttpURLConnection yc = (HttpURLConnection) oracle.openConnection();

			// 返回状态码
			System.err.println(yc.getResponseCode());

			BufferedReader in = new BufferedReader(new InputStreamReader(
					yc.getInputStream()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				json.append(inputLine);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		String msg = "[" + json.toString() + "]";

		JSONArray jsonArray = JSONArray.fromObject(msg);

		List<Map<String, Object>> mapListJson = (List) jsonArray;
		Map<String, Object> map = new HashMap<String, Object>();
		for (int i = 0; i < mapListJson.size(); i++) {
			map = mapListJson.get(i);
		}

		return map;
	}

	public static void main(String[] args) {
		String url = "http://www.ccvzb.cn/CCVZB/appservice/live/heatLives2?token=d19a6499f1cc4bde890561f181fd714f";
		String loadJSON = "[" + loadJSON(url) + "]";
		JSONArray jsonArray = JSONArray.fromObject(loadJSON);

		//json转换的list
		List<Map<String, Object>> mapListJson = (List) jsonArray;
		
		for (int i = 0; i < mapListJson.size(); i++) {
			Map<String, Object> obj = mapListJson.get(i);

			for (Entry<String, Object> entry : obj.entrySet()) {
				String strkey1 = entry.getKey();
				Object strval1 = entry.getValue();
				System.out.println("KEY:" + strkey1 + "  -->  Value:" + strval1 + "\n");
			}
		}
	}
}

  Http工具类

package com.asen.utils.http;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.json.JSONObject;

/**
 * 网络请求工具类
 * @author Asen 2017年2月19日 下午11:02:33
 *
 */
public class HttpTool {
	public static String is2Str(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int i = -1;
		while ((i = is.read()) != -1) {
			baos.write(i);
		}
		return baos.toString();
	}

	public static String doPosts(String url, NameValuePair[] nameValuePairs) {
		Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);

		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(url);
		if (nameValuePairs != null) {
			post.setRequestBody(nameValuePairs);
		}

		try {
			client.executeMethod(post);
			return is2Str(post.getResponseBodyAsStream());
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			post.releaseConnection();
		}
		return null;
	}

	public static JSONObject is2Json(String is) throws IOException {
		return new JSONObject(is);
	}

	public static JSONObject doPosts(String url, String params) throws UnsupportedEncodingException {
		Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);

		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(url);
		post.setRequestHeader("Content-Type", "application/json");
		if (params != null) {
//			post.setRequestBody(params);
			InputStream in = new ByteArrayInputStream(params.getBytes("utf-8"));
			post.setRequestBody(in);
		}

		try {
			client.executeMethod(post);
			return is2Json(is2Str(post.getResponseBodyAsStream()));
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			post.releaseConnection();
		}
		return null;
	}
	
	public static Object doPosts(String url) throws UnsupportedEncodingException {
		Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);

		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(url);
		post.setRequestHeader("Content-Type", "application/json");

		try {
			client.executeMethod(post);
			return is2Str(post.getResponseBodyAsStream());
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			post.releaseConnection();
		}
		return null;
	}

	public static JSONObject doPostsWithToken(String url, String params, String token) throws UnsupportedEncodingException {
		Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);
		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(url);
		post.setRequestHeader("Content-Type", "application/json");
		if (token != null) {
			post.setRequestHeader("Authorization", "Bearer " + token);
		}
		if (params != null) {
//			post.setRequestBody(params);
			InputStream in = new ByteArrayInputStream(params.getBytes("utf-8"));
			post.setRequestBody(in);
		}

		try {
			client.executeMethod(post);
			return is2Json(is2Str(post.getResponseBodyAsStream()));
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			post.releaseConnection();
		}
		return null;
	}

	public static int doPosts(String url, String params, String token) throws UnsupportedEncodingException {
		Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);

		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(url);
		post.setRequestHeader("Content-Type", "application/json");
		if (token != null) {
			post.setRequestHeader("Authorization", "Bearer " + token);
		}
		if (params != null) {
//			post.setRequestBody(params);
			InputStream in = new ByteArrayInputStream(params.getBytes("utf-8"));
			post.setRequestBody(in);
		}

		try {
			client.executeMethod(post);
			return post.getStatusCode();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			post.releaseConnection();
		}
		return 0;
	}

	public static int doDelete(String url, String token) {
		Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);

		HttpClient client = new HttpClient();
		DeleteMethod delete = new DeleteMethod(url);
		if (token != null) {
			delete.setRequestHeader("Authorization", "Bearer " + token);
		}

		try {
			client.executeMethod(delete);
			return delete.getStatusCode();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			delete.releaseConnection();
		}
		return 0;
	}

	public static int doPuts(String url, String params, String token) throws UnsupportedEncodingException {
		Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);

		HttpClient client = new HttpClient();
		PutMethod put = new PutMethod(url);
		if (token != null) {
			put.setRequestHeader("Authorization", "Bearer " + token);
		}
		if (params != null) {
//			put.setRequestBody(params);
			InputStream in = new ByteArrayInputStream(params.getBytes("utf-8"));
			put.setRequestBody(in);
		}

		try {
			client.executeMethod(put);
			return put.getStatusCode();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			put.releaseConnection();
		}
		return 0;
	}

	public static JSONObject doGet(String url, String token) {
		Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);

		HttpClient client = new HttpClient();
		GetMethod get = new GetMethod(url);
		get.setRequestHeader("Content-Type", "application/json");
		if (token != null) {
			get.setRequestHeader("Authorization", "Bearer " + token);
		}

		try {
			client.executeMethod(get);
			return is2Json(is2Str(get.getResponseBodyAsStream()));
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			get.releaseConnection();
		}
		return null;
	}
	
	public static String doPost(String url, NameValuePair[] nameValuePairs) {
		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(url);
		if (nameValuePairs != null) {
			post.setRequestBody(nameValuePairs);
		}

		try {
			client.executeMethod(post);
			return is2Str(post.getResponseBodyAsStream());
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			post.releaseConnection();
		}
		return null;
	}

	public static JSONObject doDelete2(String url, String token) {
		Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);
		HttpClient client = new HttpClient();
		DeleteMethod delete = new DeleteMethod(url);
		delete.setRequestHeader("Content-Type", "application/json");
		if (token != null) {
			delete.setRequestHeader("Authorization", "Bearer " + token);
		}

		try {
			client.executeMethod(delete);
			return is2Json(is2Str(delete.getResponseBodyAsStream()));
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			delete.releaseConnection();
		}
		return null;
	}
}

 

package com.asen.utils.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

public class Https {
	
    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
    	StringBuilder sb = new StringBuilder();
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            sb = new StringBuilder();
            while ((line = in.readLine()) != null) {
            	sb.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return sb.toString();
    }
}

 

package com.asen.utils.http;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

public class MySSLSocketFactory implements ProtocolSocketFactory {
	private SSLContext sslcontext = null;

	private SSLContext createSSLContext() {
		SSLContext sslcontext = null;
		try {
			sslcontext = SSLContext.getInstance("SSL");
			sslcontext.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}
		return sslcontext;
	}

	private SSLContext getSSLContext() {
		if (this.sslcontext == null) {
			this.sslcontext = createSSLContext();
		}
		return this.sslcontext;
	}

	public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
		return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
	}

	public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
		return getSSLContext().getSocketFactory().createSocket(host, port);
	}

	public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException {
		return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
	}

	public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException,
			UnknownHostException, ConnectTimeoutException {
		if (params == null) {
			throw new IllegalArgumentException("Parameters may not be null");
		}
		int timeout = params.getConnectionTimeout();
		SocketFactory socketfactory = getSSLContext().getSocketFactory();
		if (timeout == 0) {
			return socketfactory.createSocket(host, port, localAddress, localPort);
		} else {
			Socket socket = socketfactory.createSocket();
			SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
			SocketAddress remoteaddr = new InetSocketAddress(host, port);
			socket.bind(localaddr);
			socket.connect(remoteaddr, timeout);
			return socket;
		}
	}

	private static class TrustAnyTrustManager implements X509TrustManager {
		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}
	}
}

 

package com.asen.utils.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * HTTP请求类
 * @author LiHong
 */
public class HttpInvoker {

	/**
	 * GET请求
	 * @param getUrl
	 * @throws IOException
	 * @return 提取HTTP响应报文包体,以字符串形式返回
	 */
	public static String httpGet(String getUrl,Map<String, String> getHeaders) throws IOException { 
		URL getURL = new URL(getUrl); 
		HttpURLConnection connection = (HttpURLConnection) getURL.openConnection(); 

        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		if(getHeaders != null) {
			for(String pKey : getHeaders.keySet()) {
				connection.setRequestProperty(pKey, getHeaders.get(pKey));
			}
		}
		connection.connect();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		StringBuilder sbStr = new StringBuilder();
		String line;
		while ((line = bufferedReader.readLine()) != null) { 
			sbStr.append(line); 
		} 
		bufferedReader.close();
		connection.disconnect(); 
		return new String(sbStr.toString().getBytes(),"utf-8");
	}
	
	/**
	 * POST请求
	 * @param postUrl
	 * @param postHeaders
	 * @param postEntity
	 * @throws IOException
	 * @return 提取HTTP响应报文包体,以字符串形式返回
	 */
	public static String httpPost(String postUrl,Map<String, String> postHeaders, String postEntity) throws IOException {
		
		URL postURL = new URL(postUrl); 
		HttpURLConnection httpURLConnection = (HttpURLConnection) postURL.openConnection(); 
		httpURLConnection.setDoOutput(true);                 
		httpURLConnection.setDoInput(true); 
		httpURLConnection.setRequestMethod("POST"); 
		httpURLConnection.setUseCaches(false); 
		httpURLConnection.setInstanceFollowRedirects(true); 
		httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

		if(postHeaders != null) {
			for(String pKey : postHeaders.keySet()) {
				httpURLConnection.setRequestProperty(pKey, postHeaders.get(pKey));
			}
		}
		if(postEntity != null) {
			DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream()); 
			out.writeBytes(postEntity); 
			out.flush(); 
			out.close(); // flush and close 
		}
		//connection.connect(); 
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); 
		StringBuilder sbStr = new StringBuilder();
		String line;
		while ((line = bufferedReader.readLine()) != null) { 
			sbStr.append(line); 
		} 
		bufferedReader.close();
		httpURLConnection.disconnect(); 
		return new String(sbStr.toString().getBytes(),"utf-8");
	} 
	/**
	 * POST请求 ,解决中文乱码问题
	 * @param postUrl
	 * @param postHeaders
	 * @param postEntity
	 * @throws IOException
	 * @return 提取HTTP响应报文包体,以字符串形式返回
	 */
	public static String httpPost1(String postUrl,Map<String, String> postHeaders, String postEntity) throws IOException {
		
		URL postURL = new URL(postUrl); 
		HttpURLConnection httpURLConnection = (HttpURLConnection) postURL.openConnection(); 
		httpURLConnection.setDoOutput(true);                 
		httpURLConnection.setDoInput(true); 
		httpURLConnection.setRequestMethod("POST"); 
		httpURLConnection.setUseCaches(false); 
		httpURLConnection.setInstanceFollowRedirects(true); 
		httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		StringBuilder sbStr = new StringBuilder();
		if(postHeaders != null) {
			for(String pKey : postHeaders.keySet()) {
				httpURLConnection.setRequestProperty(pKey, postHeaders.get(pKey));
			}
		}
		if(postEntity != null) {
			PrintWriter out = new PrintWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(),"utf-8"));   
			out.println(postEntity);  
			out.close();  
			BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection  
			        .getInputStream()));  
			  
			String inputLine; 
			while ((inputLine = in.readLine()) != null) {  
				sbStr.append(inputLine);  
			}  
			in.close();  
		}
		httpURLConnection.disconnect(); 
		return new String(sbStr.toString().getBytes(),"utf-8");
	} 


}

 结果工具类

package com.asen.utils.result;

import java.util.HashMap;
import java.util.Map;

public class ResultMapUtils {
	
	// 成功
	public static final int SUCCESS = 0;

	// 失败
	public static final int ERROR = 1;

	// 过期
	public static final int EXPIRE = -2;
	
	/**
	 * data为空  status、msg自定义
	 * @author yangshaoping 2016年6月11日 上午10:45:03
	 * @param status
	 * @param msg
	 * @return
	 */
	public static Map<String, Object> getResult(Integer status,String msg){
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		
		map.put("status", status);
		map.put("msg", msg);
		map.put("data", data);
		
		return map;
	}
	
	/**
	 * status、msg、data自定义
	 * @author yangshaoping 2016年6月11日 上午10:46:19
	 * @param status
	 * @param msg
	 * @param data
	 * @return
	 */
	public static Map<String, Object> getResult(Integer status,String msg,Map<String, Object> data){
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("status", status);
		map.put("msg", msg);
		map.put("data", data);
		
		return map;
	}
	
	/**
	 * status为success  msg自定义、data为空
	 * @author yangshaoping 2016年6月11日 下午2:49:58
	 * @param msg
	 * @return
	 */
	public static Map<String, Object> success(String msg){
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		
		map.put("status", SUCCESS);
		map.put("msg", msg);
		map.put("data", data);
		
		return map;
		
	}
	
	/**
	 * status为success  msg、data自定义
	 * @author yangshaoping 2016年7月21日 上午10:43:59
	 * @param msg
	 * @return
	 */
	public static Map<String, Object> success(String msg , Map<String, Object> data){
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("status", SUCCESS);
		map.put("msg", msg);
		map.put("data", data);
		
		return map;
		
	}
	
	/**
	 * status为success  msg、data自定义
	 * @author yangshaoping 2016年7月21日 上午10:43:59
	 * @param msg
	 * @return
	 */
	public static Map<String, Object> success(String msg , Object data){
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("status", SUCCESS);
		map.put("msg", msg);
		map.put("data", data);
		
		return map;
	}
	
	/**
	 * status为error  msg自定义、data为空
	 * @author yangshaoping 2016年6月11日 下午2:49:58
	 * @param msg
	 * @return
	 */
	public static Map<String, Object> error(String msg){
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		
		map.put("status", ERROR);
		map.put("msg", msg);
		map.put("data", data);
		
		return map;
		
	}
	
	/**
	 * status为error 
	 * @author yangshaoping 2016年6月11日 下午2:49:58
	 * @param msg
	 * @return
	 */
	public static Map<String, Object> error(String msg,Map<String, Object> data){
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("status", ERROR);
		map.put("msg", msg);
		map.put("data", data);
		
		return map;
		
	}
	
	/**
	 * token失效
	 * @author yangshaoping 2016年7月19日 下午8:39:32
	 * @return
	 */
	public static Map<String, Object> expire(){
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		
		map.put("status", EXPIRE);
		map.put("msg", "token失效");
		map.put("data", data);
		
		return map;
		
	}
	
	/**
	 * 系统异常
	 * @author yangshaoping 2016年6月12日 上午10:13:02
	 * @param msg
	 * @return
	 */
	public static Map<String, Object> systemError(){
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		
		map.put("status", ERROR);
		map.put("msg", "系统异常");
		map.put("data", data);
		return map;
		
	}
	
	/**
	 * 系统异常
	 * @author yangshaoping 2016年7月27日 下午3:17:28
	 * @param e
	 * @return
	 */
	public static Map<String, Object> systemError(Exception e){
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		
		data.put("errorMsg", e.toString());
		
		map.put("status", ERROR);
		map.put("msg", "系统异常");
		map.put("data", data);
		return map;
	}
	
}

 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Json</groupId>
	<artifactId>Json</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>Json</name>
	<description />
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core-comm</artifactId>
			<version>4.0.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.6.3</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>1.9.1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.6.3</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<version>3.0</version>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

0
0
分享到:
评论

相关推荐

    C++工具类-常用工具类源码

    本文将深入探讨标题"**C++工具类-常用工具类源码**"所涵盖的知识点,主要围绕文件处理、编码处理、字符串处理、网络爬虫以及网页数据抓取等主题。 首先,让我们来看看文件处理方面。`FileUtil`类通常包含对文件的...

    Android开发常用工具类合集

    本资源包括常用工具类,目前收录了数组工具类、异步工具类、base64工具类、bitmap工具类、缓存工具类、时间工具类、http连接、json、IO、Map、MD5、数据库、SD卡、UbbToHtml等工具类合集

    C#工具类库类库 包含所有的常用工具类

    标题中的"C#工具类库类库 包含所有的常用工具类"暗示了这是一个集合,包含了多种实用工具类,能够极大地提升开发效率。这些工具类涵盖了从文件操作到网络通信的多个领域。 首先,FTP操作类是用于与FTP服务器进行...

    C#常用工具类代码集合Util第二版本(自己工作总结)

    C#常用工具类代码集合Util第二版本(自己工作总结),包括常用工具类,扩展方法工具类,百度地图C#工具类,Echart工具类,Office工具类,Autofac工具类,Web开发常用工具类,Winform开发常用工具类,是自己工作十年...

    Java常用工具类大全,工作5年精心整理.zip

    "Java常用工具类大全,工作5年精心整理.zip"这个压缩包文件很可能包含了一位有经验的Java开发者在五年工作中积累的各种实用工具类,这些工具类能够极大地提高开发效率,简化代码编写。以下是对可能包含的知识点进行...

    C#.net常用工具类,全部源码

    本文将深入探讨“C#.net常用工具类,全部源码”这一主题,涵盖其核心概念、功能以及如何利用这些工具类提高开发效率。 首先,"常用工具类"是指在开发过程中频繁使用的、通用的类库,它们提供了许多常见的功能,如...

    自己整理的C#常用工具类

    在C#编程中,工具类(Utility Class)是一种常见的设计模式,它封装了一些常用的功能,以便在项目中方便地重复使用。这些工具类通常包含静态方法,不涉及实例化,直接通过类名调用,降低了代码冗余,提高了代码复用...

    Android代码-AyoLang常用工具类

    常用工具类,java函数糖,安卓函数糖 没整到jcenter上,暂时就用aar包吧,也挺省劲:下载地址 下载下来文件名是:ayo-lang.aar,拷到libs目录里 然后在build.gradle里引入: repositories { flatDir { dirs 'libs'...

    Java常用工具类

    Java常用工具类是Java开发中不可或缺的一部分,它们提供了一系列便捷的方法,帮助开发者高效地处理各种常见任务。在Java中,最著名的工具类库是`java.util`包,它包含了大量实用类,如集合、日期时间、数学计算、...

    开发常用工具类

    "开发常用工具类"这个主题涵盖了各种不同领域的实用功能,例如字符串处理、日期时间操作、集合操作等。下面将详细介绍这些工具类中的常见知识点: 1. **字符串工具类**: - `StringUtils`:Apache Commons Lang ...

    安卓开发框架工具类相关-Android快速开发系列10个常用工具类.rar

    【标题】"安卓开发框架工具类相关-Android快速开发系列10个常用工具类.rar" 涉及的是Android应用程序开发中的一个关键方面——工具类的集合。在Android开发中,工具类通常包含一系列静态方法,用于执行常见的、重复...

    java常用工具类

    "java常用工具类"这个主题涵盖了Java开发中常用的类和方法,这些工具类可以帮助我们简化编程工作,提高代码的可读性和可维护性。在Java中,`java.util`包就是这样一个包含大量工具类的包,提供了很多实用的功能。 1...

    java开发常用工具类大全,程序员必备工具

    本文将详细解析“java开发常用工具类大全”中涉及的关键知识点,包括但不限于输入字符校验、数据转换、网络操作、加密解密、JSON处理、图像操作以及数据库操作。 1. **输入字符校验类**: 这类工具通常包含对字符...

    java常用工具类集合(也有转自他人的)

    "java常用工具类集合"是一个综合性的资源,它包含了从不同来源收集的实用工具类,旨在帮助开发者提高效率,减少代码重复。下面,我们将深入探讨这个主题,分析其中可能包含的知识点。 首先,`opslabJutil-master....

    java开发常用工具类

    本文将详细解析"java开发常用工具类"中的关键知识点,包括日历、时间处理、Excel导出、网络请求、流操作、数据处理、数值计算以及XML和Web工具类。 1. **日历和时间处理**: Java中`java.util.Calendar`和`java....

    Java常用工具类包包含各种常用开发工具

    "Java常用工具类包"是一个集合,它包含了多种针对不同场景的工具类,如文件操作、文本处理、对象转换等。下面将详细介绍这些工具类的主要功能及其应用场景。 1. **文件对比**: - Java中的`java.io.File`类可以...

    java常用工具类整理

    "java常用工具类整理"这个主题涵盖了Java开发中常用的工具类,这些类在日常编程中非常实用,能大大提高开发效率。这里我们将深入探讨一些常见的Java工具类,并结合`com-jarvis-base`这个文件名,推测这是一个基础...

Global site tag (gtag.js) - Google Analytics