Fork me on GitHub

常用工具类

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>

 

 

posted @ 2017-02-20 20:40  阿森丶  阅读(216)  评论(0编辑  收藏  举报