JavaWeb接入微博第三方登陆

@TOC

首先必须注册微博开放平台并且提交信息的操作

微博开放平台 :点我进入
点击我的应用
进来之后去创建应用,如果是网站的就创建网站的就可以了~ 点我

如果这些审核不明白的可以找我QQ: 2501521908

过应用审核什么的就不用多说了,域名不用备案,并且微博也会给你通知告诉你应该怎么怎么做,具体的界面如下:
微博的一些审核


关于应用高级信息

应用高级信息:
高级信息

  1. 回调地址 ,则就是用户登陆成功之后微博返回给你code的地方,也就是我们后台处理这些信息的地址;
  2. 取消回调的地址 就是跳转到登陆的地址后,人家点了取消,应该跳转哪里处理信息的地址;

正常使用的应用截图:

可以使用的应用

  • 这里提示我们微博的广场下线了,现在的进度条已经可以够我们肆意妄为的了~

下载微博官方给的demo部分并配置:

  • GitHub地址: 点我
  • 进去之后直接下载好demo,配置自己的key和密钥

配置的教程:

  • 下载好demo之后先别急着复制成web项目,可以按照github下面说的运行一下,看看自己的发起等有没有问题,可以运行就排除了后期的很多麻烦
  • 此处应该注意的是: 配置文件上的回调地址需要在应用之前提前配好并且两处一致才可以

配置文件

配置事项:

client_ID = 你的appid
client_SERCRET = 秘钥(支持重置在高级信息里)
redirect_URI =  (你配置的回调地址)
baseURL=https://api.weibo.com/2/
accessTokenURL=https://api.weibo.com/oauth2/access_token
authorizeURL=https://api.weibo.com/oauth2/authorize
rmURL=https://rm.api.weibo.com/2/

然后可以结合GitHub上Doc的试试看看能不能发起一下


正式的撸代码部分:

首先说下,我的是maven的结构,可以自己下载这些jar包放到: /WEB-INF/lib/
maven的大佬请忽略这句话!

我弄得测试的demo的maven依赖

展开查看代码

<dependencies>  
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId> 
            <version>3.1</version>  
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.3</version>
            <classifier>jdk15</classifier><!--指定jdk版本 -->
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.44</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>  
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>   
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>      
        <!-- https://mvnrepository.com/artifact/com.belerweb/weibo4j-oauth2 -->
        <dependency>
            <groupId>com.belerweb</groupId>
            <artifactId>weibo4j-oauth2</artifactId>
            <version>2.1.1-beta2-3</version>
        </dependency>  
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.9</version>
        </dependency>
    </dependencies>


微博有去maven发布仓库,复制依赖使用即可


合成的部分

去把GitHub上下载好的项目里的这两个拿到自己的项目里,一些微博写的工具
复制


整合自己项目中

我的只是个小小的demo,所以没有那么多信息,只是简简单单的,具体的可以根据自己项目跑起来来更换

index.jsp 首页

<a href="/dologin.do">点我进行微博登陆</a>

dologin.do 发起微博登陆的action

        Oauth oauth = new Oauth();
        String url = null;
        try {
            url = oauth.authorize("code", null);
        } catch (WeiboException e) {
            e.printStackTrace();
        }
        response.sendRedirect(url);

auth.do 接收微博返回并且处理的action

注意:这里也得跟配置 config.properties文件一样,需要你配置一致可以正确拿到你想要的

展开查看代码

    /**
       这里的常量需要配置成自己的appid等
    **/
    //常量
    private final static String CLIENT_ID = "appid";
    private final static String CLIENT_SERCRET = "秘钥";
    private final static String GET_TOKEN_URL = "https://api.weibo.com/oauth2/access_token";
    private final static String REDIRECT_URI = "回调地址";
    private final static String GET_USER_INFO = "https://api.weibo.com/2/users/show.json";
    private final static String GET_TOKEN_INFO_URL = "https://api.weibo.com/oauth2/get_token_info";
    private final static String STATE = "register";

    //action部分
    response.setContentType("text/html;charset=UTF-8");
        // 获取code
        String code = request.getParameter("code");
        String access_token = "";
        String expires_in = "";
        String uid = "";

        // 获取token
        JSONObject token = null;
        try {
            token = getAccessToken(code);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            access_token = token.getString("access_token");
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        try {
            uid = token.getString("uid");
            System.out.println(uid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            expires_in = String.valueOf(token.getInt("expires_in"));
            System.out.println(expires_in);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // 获取用户信息
        JSONObject userInfo = null;
        try {
            userInfo = getUserInfo(access_token, uid);
            request.setAttribute("userInfo", userInfo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            String nickname = userInfo.getString("screen_name");
            request.setAttribute("nickname", nickname);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            String profile_image_url = userInfo.getString("profile_image_url");
            request.setAttribute("profile_image_url", profile_image_url);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            String gender = "f".equals(userInfo.getString("gender")) ? "1" : "0";
            request.setAttribute("gender", gender);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        request.getRequestDispatcher("auth.jsp").forward(request, response);
 

   //定义到自己可以调用的地方

    /**
     * 获取AccessToken
     * 
     * @throws JSONException
     */
    private JSONObject getAccessToken(String code) throws JSONException {
        StringBuilder sb = new StringBuilder();
        sb.append("grant_type=authorization_code");
        sb.append("&client_id=" + CLIENT_ID);
        sb.append("&client_secret=" + CLIENT_SERCRET);
        sb.append("&redirect_uri=" + REDIRECT_URI);
        sb.append("&code=" + code);
        String result = HttpsUtil.post(GET_TOKEN_URL, sb.toString());
        /**
         * 返回数据 { "access_token": "ACCESS_TOKEN", "expires_in": 1234,
         * "remind_in":"798114", "uid":"12341234" }
         */
        JSONObject json = new JSONObject(result);
        return json;
    }

    /**
     * 获取用户信息
     * 
     * @param access_token
     * @param uid
     *            查询的用户ID
     * @return
     * @throws JSONException
     */
    private JSONObject getUserInfo(String access_token, String uid) throws JSONException {
        StringBuilder sb = new StringBuilder();
        sb.append("?access_token=" + access_token);
        sb.append("&uid=" + uid);
        String result = HttpsUtil.get(GET_USER_INFO + sb.toString());
        // 返回参数:查看http://open.weibo.com/wiki/2/users/show
        JSONObject json = new JSONObject(result);
        return json;
    }


嗯,复制完这些你会发现,wc还是会编译错误,导入所有的包之后,还是会编译错误
20190228190343639.jpg
这狗博主不会让我白弄了吧~???
不会的 嘿嘿
因为这里差了几个工具类,建议放在自己项目的util包下,看起来好整理

HttpsUtil.java 请求工具类

展开查看代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang3.StringUtils;

import com.zhangshuaike.utils.MyX509TrustManager;

public class HttpsUtil {
    /**
     * post请求方法
     */
    private static final String METHOD_POST = "POST";

    /**
     * utf-8编码格式
     */
    private static final String DEFAULT_CHARSET = "utf-8";

    /**
     * doPost
     * 
     * @param url
     *            请求地址
     * @param params
     *            请求参数
     * @param charset
     *            编码
     * @param ctype
     *            类型
     * @param connectTimeout
     *            连接超时时间
     * @param readTimeout
     *            读取超时时间
     * @return 结果
     * @throws Exception
     *             异常
     */
    public static String doPost(String url, String params, String charset, String ctype, int connectTimeout,
            int readTimeout) throws Exception {
        charset = (charset == null || "".equals(charset)) ? DEFAULT_CHARSET : charset;
        byte[] content = {};
        if (params != null) {
            content = params.getBytes(charset);
        }
        return doPost(url, ctype, content, connectTimeout, readTimeout);
    }

    /**
     * doPost
     * 
     * @param url
     *            请求地址
     * @param ctype
     *            类型
     * @param content
     *            内容
     * @param connectTimeout
     *            连接超时时间
     * @param readTimeout
     *            读取超时时间
     * @return 结果
     * @throws Exception
     *             异常
     */
    public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout)
            throws Exception {
        HttpsURLConnection conn = null;
        OutputStream out = null;
        String rsp = null;
        try {
            try {
                SSLContext ctx = SSLContext.getInstance("TLS");
                ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
                SSLContext.setDefault(ctx);

                conn = getConnection(new URL(url), METHOD_POST, ctype);
                conn.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });
                conn.setConnectTimeout(connectTimeout);
                conn.setReadTimeout(readTimeout);
            } catch (Exception e) {
                // log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
                throw e;
            }
            try {
                out = conn.getOutputStream();
                out.write(content);
                rsp = getResponseAsString(conn);
            } catch (IOException e) {
                // log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
                throw e;
            }

        } finally {
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }

        return rsp;
    }

    private static class DefaultTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

    }

    /**
     * 获取连接
     * 
     * @param url
     *            请求地址
     * @param method
     *            请求方法
     * @param ctype
     *            类型
     * @return HttpsURLConnection
     * @throws IOException
     *             异常
     */
    private static HttpsURLConnection getConnection(URL url, String method, String ctype) throws IOException {
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");
        conn.setRequestProperty("User-Agent", "stargate");
        conn.setRequestProperty("Content-Type", ctype);
        return conn;
    }

    /**
     * getResponseAsString
     * 
     * @param conn
     *            conn连接
     * @return String
     * @throws IOException
     *             IOException
     */
    protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
        String charset = getResponseCharset(conn.getContentType());
        InputStream es = conn.getErrorStream();
        if (es == null) {
            return getStreamAsString(conn.getInputStream(), charset);
        } else {
            String msg = getStreamAsString(es, charset);
            if (StringUtils.isEmpty(msg)) {
                throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
            } else {
                throw new IOException(msg);
            }
        }
    }

    /**
     * getStreamAsString
     * 
     * @param stream
     *            stream
     * @param charset
     *            charset
     * @return String
     * @throws IOException
     *             IOException
     */
    private static String getStreamAsString(InputStream stream, String charset) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
            StringWriter writer = new StringWriter();

            char[] chars = new char[256];
            int count = 0;
            while ((count = reader.read(chars)) > 0) {
                writer.write(chars, 0, count);
            }

            return writer.toString();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    /**
     * getResponseCharset
     * 
     * @param ctype
     *            ctype
     * @return String
     */
    private static String getResponseCharset(String ctype) {
        String charset = DEFAULT_CHARSET;

        if (!StringUtils.isEmpty(ctype)) {
            String[] params = ctype.split(";");
            for (String param : params) {
                param = param.trim();
                if (param.startsWith("charset")) {
                    String[] pair = param.split("=", 2);
                    if (pair.length == 2) {
                        if (!StringUtils.isEmpty(pair[1])) {
                            charset = pair[1].trim();
                        }
                    }
                    break;
                }
            }
        }
        return charset;
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    /**
     * doGet
     * 
     * @param url
     *            请求地址
     * @param keyValueParams
     *            参数
     * @param cypt
     *            cypt
     * @return String
     * @throws Exception
     *             Exception
     */
    public static String doGet(String url, Map<String, String> keyValueParams, String cypt) throws Exception {
        String result = "";
        BufferedReader in = null;
        try {

            String urlStr = url + "?" + getParamStr(keyValueParams);
            // System.out.println("GET请求的URL为:"+urlStr);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new DefaultTrustManager() }, new java.security.SecureRandom());
            URL realUrl = new URL(urlStr);
            // 打开和URL之间的连接
            HttpsURLConnection connection = (HttpsURLConnection) realUrl.openConnection();
            // 设置https相关属性
            connection.setSSLSocketFactory(sc.getSocketFactory());
            connection.setHostnameVerifier(new TrustAnyHostnameVerifier());
            connection.setDoOutput(true);

            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("Content-type", cypt);
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            // System.out.println("获取的结果为:"+result);
        } catch (Exception e) {
            // System.out.println("发送GET请求出现异常!" + e);
            // e.printStackTrace();
            throw e;
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                // e2.printStackTrace();
                throw e2;
            }
        }
        return result;
    }

    /**
     * 转化字符串参数
     * 
     * @param params
     *            参数
     * @return String
     */
    public static String getParamStr(Map<String, String> params) {
        String paramStr = StringUtils.EMPTY;
        if (null == params || 0 == params.size()) {
            return paramStr;
        }
        // 获取参数列表组成参数字符串
        for (String key : params.keySet()) {
            paramStr += key + "=" + params.get(key) + "&";
        }
        // 去除最后一个"&"
        return paramStr.substring(0, paramStr.length() - 1);
    }

    /**
     * 解析出url参数中的键值对 如 "index.jsp?Action=del&id=123",解析出Action:del,id:123存入map中
     * 
     * @param url
     *            url地址
     * @return url请求参数部分
     * @author lzf
     */
    public static Map<String, String> getUrlParam(String url) {
        // 初始化返回
        Map<String, String> params = new HashMap<String, String>();
        if (StringUtils.isBlank(url)) {
            return params;
        }
        //
        String strUrlParam = truncateUrl(url);
        if (StringUtils.isBlank(strUrlParam)) {
            return params;
        }
        String[] arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = strSplit.split("[=]");
            // 解析出键值
            if (arrSplitEqual.length > 1) {
                // 正确解析
                params.put(arrSplitEqual[0], arrSplitEqual[1]);
            } else {
                if (!"".equals(arrSplitEqual[0])) {
                    // 只有参数没有值,也加入
                    params.put(arrSplitEqual[0], "");
                }
            }
        }
        return params;
    }

    /**
     * 去掉url中的路径,留下请求参数部分
     * 
     * @param url
     *            url地址
     * @return url
     * @author lzf
     */
    private static String truncateUrl(String url) {
        String strAllParam = null;
        String[] arrSplit = null;
        url = url.trim();
        arrSplit = url.split("[?]");
        if (url.length() > 1) {
            if (arrSplit.length > 1) {
                for (int i = 1; i < arrSplit.length; i++) {
                    strAllParam = arrSplit[i];
                }
            }
        }
        return strAllParam;
    }


 
 
    /**
     * HTTPS 的get 请求
     * @param url
     * @return
     */
    public static String get(String url) {
        StringBuffer bufferRes = null;
        try {
            TrustManager[] tm = { new MyX509TrustManager() };  
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
            sslContext.init(null, tm, new java.security.SecureRandom());  
            // 从上述SSLContext对象中得到SSLSocketFactory对象  
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            
            URL urlGet = new URL(url);
            HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
            // 连接超时
            http.setConnectTimeout(25000);
            // 读取超时 --服务器响应比较慢,增大时间
            http.setReadTimeout(25000);
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setSSLSocketFactory(ssf);
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            
            InputStream in = http.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
            String valueString = null;
            bufferRes = new StringBuffer();
            while ((valueString = read.readLine()) != null){
                bufferRes.append(valueString);
            }
            in.close();
            if (http != null) {
                // 关闭连接
                http.disconnect();
            }
            return bufferRes.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * get请求https
     * @param url
     * @param params
     * @return
     */
    public static String get(String url, Map<String, String> params) {
        return get(initParams(url, params));
    }
    
    /**
     * HTTPS 的POST 请求
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, String params) {
        StringBuffer bufferRes = null;
        try {
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象  
            SSLSocketFactory ssf = sslContext.getSocketFactory();
 
 
            URL urlGet = new URL(url);
            HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
            // 连接超时
            http.setConnectTimeout(25000);
            // 读取超时 --服务器响应比较慢,增大时间
            http.setReadTimeout(25000);
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setSSLSocketFactory(ssf);
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
 
 
            OutputStream out = http.getOutputStream();
            out.write(params.getBytes("UTF-8"));
            out.flush();
            out.close();
 
 
            InputStream in = http.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
            String valueString = null;
            bufferRes = new StringBuffer();
            while ((valueString = read.readLine()) != null){
                bufferRes.append(valueString);
            }
            in.close();
            if (http != null) {
                // 关闭连接
                http.disconnect();
            }
            return bufferRes.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
 
    /**
     * 构造请求参数
     * @param url
     * @param params
     * @return
     */
    public static String initParams(String url, Map<String, String> params){
        if (null == params || params.isEmpty()) {
            return url;
        }
        StringBuilder sb = new StringBuilder(url);
        if (url.indexOf("?") == -1) {
            sb.append("?");
        } else {
            sb.append("&");
        }
        boolean first = true;
        for (Entry<String, String> entry : params.entrySet()) {
            if (first) {
                first = false;
            } else {
                sb.append("&");
            }
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key).append("=");
            if (StringUtils.isNotEmpty(value)) {
                try {
                    sb.append(URLEncoder.encode(value, DEFAULT_CHARSET));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}

JsonUtil.java json串的工具类

展开查看代码

import java.text.SimpleDateFormat;     
import java.util.ArrayList;     
import java.util.Collection;     
import java.util.Date;     
import java.util.HashMap;     
import java.util.Iterator;     
import java.util.List;     
import java.util.Map;     
    
import net.sf.ezmorph.MorpherRegistry;     
import net.sf.ezmorph.object.DateMorpher;     
import net.sf.json.JSONArray;     
import net.sf.json.JSONObject;     
import net.sf.json.JsonConfig;     
import net.sf.json.processors.JsonValueProcessor;     
import net.sf.json.util.JSONUtils;     
import net.sf.json.xml.XMLSerializer;     
    
public class JsonUtil {     
    

    /**   
    * 从json串转换成实体对象   
    * @param jsonObjStr e.g. {'name':'get','dateAttr':'2009-11-12'}   
    * @param clazz Person.class   
    * @return   
    */    
    public static Object getDtoFromJsonObjStr(String jsonObjStr, Class clazz) {     
        return JSONObject.toBean(JSONObject.fromObject(jsonObjStr), clazz);     
    }     
    
    /**   
    * 从json串转换成实体对象,并且实体集合属性存有另外实体Bean   
    * @param jsonObjStr e.g. {'data':[{'name':'get'},{'name':'set'}]}   
    * @param clazz e.g. MyBean.class   
    * @param classMap e.g. classMap.put("data", Person.class)   
    * @return Object   
    */    
    public static Object getDtoFromJsonObjStr(String jsonObjStr, Class clazz, Map classMap) {     
        return JSONObject.toBean(JSONObject.fromObject(jsonObjStr), clazz, classMap);     
    }     
    
    /**   
    * 把一个json数组串转换成普通数组   
    * @param jsonArrStr  e.g. ['get',1,true,null]   
    * @return Object[]   
    */    
    public static Object[] getArrFromJsonArrStr(String jsonArrStr) {     
        return JSONArray.fromObject(jsonArrStr).toArray();     
    }     
    
    /**   
    * 把一个json数组串转换成实体数组   
    * @param jsonArrStr e.g. [{'name':'get'},{'name':'set'}]   
    * @param clazz e.g. Person.class   
    * @return Object[]   
    */    
    public static Object[] getDtoArrFromJsonArrStr(String jsonArrStr, Class clazz) {     
        JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);     
        Object[] objArr = new Object[jsonArr.size()];     
        for (int i = 0; i < jsonArr.size(); i++) {     
            objArr[i] = JSONObject.toBean(jsonArr.getJSONObject(i), clazz);     
        }     
        return objArr;     
    }     
    
    /**   
    * 把一个json数组串转换成实体数组,且数组元素的属性含有另外实例Bean   
    * @param jsonArrStr e.g. [{'data':[{'name':'get'}]},{'data':[{'name':'set'}]}]   
    * @param clazz e.g. MyBean.class   
    * @param classMap e.g. classMap.put("data", Person.class)   
    * @return Object[]   
    */    
    public static Object[] getDtoArrFromJsonArrStr(String jsonArrStr, Class clazz,     
            Map classMap) {     
        JSONArray array = JSONArray.fromObject(jsonArrStr);     
        Object[] obj = new Object[array.size()];     
        for (int i = 0; i < array.size(); i++) {     
            JSONObject jsonObject = array.getJSONObject(i);     
            obj[i] = JSONObject.toBean(jsonObject, clazz, classMap);     
        }     
        return obj;     
    }     
    
    /**   
    * 把一个json数组串转换成存放普通类型元素的集合   
    * @param jsonArrStr  e.g. ['get',1,true,null]   
    * @return List   
    */    
    public static List getListFromJsonArrStr(String jsonArrStr) {     
        JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);     
        List list = new ArrayList();     
        for (int i = 0; i < jsonArr.size(); i++) {     
            list.add(jsonArr.get(i));     
        }     
        return list;     
    }     
    
    /**   
    * 把一个json数组串转换成集合,且集合里存放的为实例Bean   
    * @param jsonArrStr e.g. [{'name':'get'},{'name':'set'}]   
    * @param clazz   
    * @return List   
    */    
    public static List getListFromJsonArrStr(String jsonArrStr, Class clazz) {     
        JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);     
        List list = new ArrayList();     
        for (int i = 0; i < jsonArr.size(); i++) {     
            list.add(JSONObject.toBean(jsonArr.getJSONObject(i), clazz));     
        }     
        return list;     
    }     
    
    /**   
    * 把一个json数组串转换成集合,且集合里的对象的属性含有另外实例Bean   
    * @param jsonArrStr e.g. [{'data':[{'name':'get'}]},{'data':[{'name':'set'}]}]   
    * @param clazz e.g. MyBean.class   
    * @param classMap e.g. classMap.put("data", Person.class)   
    * @return List   
    */    
    public static List getListFromJsonArrStr(String jsonArrStr, Class clazz, Map classMap) {     
        JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);     
        List list = new ArrayList();     
        for (int i = 0; i < jsonArr.size(); i++) {     
            list.add(JSONObject.toBean(jsonArr.getJSONObject(i), clazz, classMap));     
        }     
        return list;     
    }     
    
    /**   
    * 把json对象串转换成map对象   
    * @param jsonObjStr e.g. {'name':'get','int':1,'double',1.1,'null':null}   
    * @return Map   
    */    
    public static Map getMapFromJsonObjStr(String jsonObjStr) {     
        JSONObject jsonObject = JSONObject.fromObject(jsonObjStr);     
    
        Map map = new HashMap();     
        for (Iterator iter = jsonObject.keys(); iter.hasNext();) {     
            String key = (String) iter.next();     
            map.put(key, jsonObject.get(key));     
        }     
        return map;     
    }     
    
    /**   
    * 把json对象串转换成map对象,且map对象里存放的为其他实体Bean   
    * @param jsonObjStr e.g. {'data1':{'name':'get'},'data2':{'name':'set'}}   
    * @param clazz e.g. Person.class   
    * @return Map   
    */    
    public static Map getMapFromJsonObjStr(String jsonObjStr, Class clazz) {     
        JSONObject jsonObject = JSONObject.fromObject(jsonObjStr);     
    
        Map map = new HashMap();     
        for (Iterator iter = jsonObject.keys(); iter.hasNext();) {     
            String key = (String) iter.next();     
            map.put(key, JSONObject.toBean(jsonObject.getJSONObject(key), clazz));     
        }     
        return map;     
    }     
    
    /**   
     * 把json对象串转换成map对象,且map对象里存放的其他实体Bean还含有另外实体Bean   
     * @param jsonObjStr e.g. {'mybean':{'data':[{'name':'get'}]}}   
     * @param clazz e.g. MyBean.class   
     * @param classMap  e.g. classMap.put("data", Person.class)   
     * @return Map   
     */    
    public static Map getMapFromJsonObjStr(String jsonObjStr, Class clazz, Map classMap) {     
        JSONObject jsonObject = JSONObject.fromObject(jsonObjStr);     
    
        Map map = new HashMap();     
        for (Iterator iter = jsonObject.keys(); iter.hasNext();) {     
            String key = (String) iter.next();     
            map.put(key, JSONObject     
                    .toBean(jsonObject.getJSONObject(key), clazz, classMap));     
        }     
        return map;     
    }     
    
   

JsonUtil.java需要使用的一个接口

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class MyX509TrustManager implements X509TrustManager {

      {
      }

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

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

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        
    }

这些都处理完之后,确定可以请求之后,弄上最后的显示数据的jsp,就ok啦,大功告成

auth.jsp 数据的显示层

刚刚登陆的所有用户信息${userInfo}

用户名:${nickname}

头像:<img src="${profile_image_url}">

性别:${gender} 

总结和帮助

  • 怎么确定微博,这次登陆成功,直接在数据库注册,下次直接查库?
    答: 微博返回的uid是唯一的,可以数据库加列设置一个根据uid查的方法
  • 这个jsp上面没显示出来我要显示的信息,但是微博官方提供
    答: ${userInfo} 这里已经取到了所有数据,可以根据相应的键get,存储相应的作用域就可以了!
看完上面还没明白?

可以加我的一些联系方式,来一起研究
QQ: 2501521908
Mail: admin@957xx.cc

最后修改:2019 年 02 月 28 日 09 : 48 PM
如果觉得我的文章对你有用,请随意赞赏

发表评论