ssh开发微信公众号java获取微信用户信息代码有误, 50C

这是action代码

  package com.tyol.ljtg.index.action;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.tyol.ljtg.pojo.SNSUserInfo;
import com.tyol.ljtg.pojo.WeixinOauth2Token;
import com.tyol.ljtg.products.service.ProductService;
import com.tyol.ljtg.products.vo.Products;
import com.tyol.ljtg.users.service.UserService;
import com.tyol.ljtg.users.vo.Users;
import com.tyol.ljtg.utils.MyX509TrustManager;
/**
 * 首页登录的action
 * 
 *
 * 
 */
public class IndexAction extends ActionSupport implements ModelDriven<Users>{

    private static final long serialVersionUID = 1L;
    private String code ;
    private String state ;
    public void setCode(String code) {
        this.code = code;
    }
    public void setState(String state) {
        this.state = state;
    }
    private Users users = new Users() ;
    public void setUsers(Users users) {
        this.users = users;
    }
    //注入UserService 
    private UserService userService ;
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    //注入ProductService
    private ProductService productService ;
    public void setProductService(ProductService productService) {
        this.productService = productService;
    }

    public String execute(){
        //用户同意授权后,能获取到code
     // 用户同意授权
            if (!"authdeny".equals(code)) {
                System.out.println(221);
            // 获取网页授权access_token
            WeixinOauth2Token weixinOauth2Token = getOauth2AccessToken("wx01fe15e40c010d99", "b781d53947b374324ae5a68642b79a57", code);
            // 网页授权接口访问凭证
            String accessToken = weixinOauth2Token.getAccessToken();
            // 用户标识
            String openId = weixinOauth2Token.getOpenId();
            // 获取用户信息
            SNSUserInfo snsUserInfo = getSNSUserInfo(accessToken, openId);
            //设置微信用户信息
            users.setUid(snsUserInfo.getOpenId());
            users.setUsername(snsUserInfo.getNickname());
            users.setAddress(snsUserInfo.getCity());
            users.setHeadImgUrl(snsUserInfo.getHeadImgUrl());
            //保存用户
              userService.addUsers(users);
            List<Products> products = productService.findAllProducts();
            ServletActionContext.getRequest().getSession().setAttribute("products", products);
            ServletActionContext.getRequest().getSession().setAttribute("users", users);
            return "indexOne";
        }
        users = userService.findByUid("111");
        List<Products> products = productService.findAllProducts();
        ServletActionContext.getRequest().getSession().setAttribute("products", products);
        ServletActionContext.getRequest().getSession().setAttribute("users", users);
        return "index";
    }
    /**
     * 获取网页授权凭证
     * 
     * @param appId 公众账号的唯一标识
     * @param appSecret 公众账号的密钥
     * @param code
     * @return WeixinAouth2Token
     */
    public static WeixinOauth2Token getOauth2AccessToken(String appId, String appSecret, String code) {
        WeixinOauth2Token wat = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        requestUrl = requestUrl.replace("APPID", "wx01fe15e40c010d99");
        requestUrl = requestUrl.replace("SECRET", "b781d53947b374324ae5a68642b79a57");
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证

        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
            try {
                wat = new WeixinOauth2Token();
                wat.setAccessToken(jsonObject.getString("access_token"));
                wat.setExpiresIn(jsonObject.getInt("expires_in"));
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setScope(jsonObject.getString("scope"));
            } catch (Exception e) {
                wat = null;
                int errorCode = jsonObject.getInt("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                System.out.println(111);
            }
        }
        return wat;
    }
    /**
     * 发送https请求
     * 
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            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 url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);

            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            ce.addSuppressed(ce);
        } catch (Exception e) {
            e.addSuppressed(e);
        }
        return jsonObject;
    }
    /**
     * 通过网页授权获取用户信息
     * 
     * @param accessToken 网页授权接口调用凭证
     * @param openId 用户标识
     * @return SNSUserInfo
     */
    @SuppressWarnings( { "deprecation", "unchecked" })
    public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) {
        SNSUserInfo snsUserInfo = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", "wx01fe15e40c010d99");
        // 通过网页授权获取用户信息
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                snsUserInfo = new SNSUserInfo();
                // 用户的标识
                snsUserInfo.setOpenId(jsonObject.getString("openid"));
                // 昵称
                snsUserInfo.setNickname(jsonObject.getString("nickname"));
                // 性别(1是男性,2是女性,0是未知)
                snsUserInfo.setSex(jsonObject.getInt("sex"));
                // 用户所在国家
                snsUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                snsUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                snsUserInfo.setCity(jsonObject.getString("city"));
                // 用户头像
                snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
                // 用户特权信息
                snsUserInfo.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));
            } catch (Exception e) {
                snsUserInfo = null;
                int errorCode = jsonObject.getInt("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                System.out.println(111);
            }
        }
        return snsUserInfo;
    }
    @Override
    public Users getModel() {
        // TODO Auto-generated method stub
        return users;
    }
}


1个回答

你应该把你报我错贴出来

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问