最简单暴力获取openId的方法。

废话不多说直接上代码。

这里是获取微信openid的,只需要前台调用定义好的接口,就会把openid返回给前台。或者自行保存。

 

package com.ckugua.mentality.controller;


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

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.poi.util.IOUtils;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ckugua.mentality.util.JsonUtil;


//获取openid
@Controller
@RequestMapping("/wx/user")
public class UserController  {

    @ResponseBody 
    @RequestMapping("/huoquOpenid") 
    public String getUserInfo(@RequestParam(name= "code")String code) throws Exception {
        Map<String,Object> rtnMap = new HashMap<String,Object>();
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        url += "?appid=";//自己的appid
        url += "&secret=";//密匙
        url += "&js_code=" + code;
        url += "&grant_type=authorization_code";
        byte[] res = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
            res = IOUtils.toByteArray(response.getEntity().getContent());
        } catch (Exception e) {
            throw e;
        } finally {
            if (httpget != null) {
                httpget.abort();
            }
            httpclient.getConnectionManager().shutdown();
        }
        JSONObject jo = JSON.parseObject(new String(res, "utf-8"));
        String openid = jo.getString("openid");
     
        return openid;
    }
}

 

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值