金沙澳门官网7817网址微信java开拓之落成微信主动推送新闻

2.拉取用户信息,4.接口貌似要申请权限,/,Toast.LENGTH,”请求超时”,阿伦网络工作室

金沙澳门官网7817网址 4

您大概感兴趣的稿子:

  • java微信支付第3步
    获取消息和死灰复燃音讯
  • java微信公司号支付之发送消息(文本、图片、语音)
  • JAVA达成springMVC格局的微信接入、完成新闻自动回复实例
  • Java开采微信公众号接到和丧气回复普通信息
  • Java微信二次开采(二)
    Java微信文本音信接口请求与发送
  • Java微信公众平台支付(五)
    文本及图文消息回复的落到实处
  • 微信支付java版本之JSAPI支付+发送模板音讯
  • java微信支付API第一步
    获取和苏醒新闻
  • Java微信公众平台开垦(贰)
    微信服务器post音讯体的吸纳
  • java实现微信公众号发送模版音讯

腾讯OAuth授权联合登6,oauth授权联合登6

/**
* unionLoginCallbackPath
*/
@Value(“${QQ_UNION_LOGIN_CALLBACK_PATH}”)
private String qqUnionLoginCallbackPath;
/**
* appKey
*/
@Value(“${QQ_CONSUMER_KEY}”)
private String appKey;
/**
* appSecret
*/
@Value(“${QQ_CONSUMER_SECRET}”)
private String appSecret;
/**
* loginUrl
*/
@Value(“${QQ_LOGIN_URL}”)
private String loginUrl;
/**
* accessTokenUrl
*/
@Value(“${QQ_ACCESS.TOKEN_URL}”)
private String accessTokenUrl;
/**
* openIdUrl
*/
@Value(“${QQ_OPEN_ID_URL}”)
private String openIdUrl;
/**
* userInfoUrl
*/
@Value(“${QQ_USER_INFO_URL}”)
private String userInfoUrl;

public QQUnionLoginApi() {}

/**
* 获得QQ登陆UXC60L,第一步流程
* @param callBackPage
* @return
*/
public String getQQLoginUrl() {

// 获取QQ登陆页面包车型客车url
StringBuilder qqLoginUrl = new StringBuilder();

// QQ登录地方 用于获取Authorization Code
qqLoginUrl.append(this.loginUrl);

// 授权类型,此值固定为“code”
qqLoginUrl.append(“?response_type=code”);

// 申请QQ登伍分三功后,分配给采取的appid
qqLoginUrl.append(“&client_id=” + this.appKey);

// 成功授权后的回调地址,提出安装为网址首页或网址的用户核心。
qqLoginUrl.append(“&redirect_uri=” + qqUnionLoginCallbackPath);

//
请求用户授权时向用户体现的可进展授权的列表。借使要填写五个接口名称,请用逗号隔断。
不传则暗中同意请求对接口get_user_info实行授权
qqLoginUrl.append(“&scope=”);

//
client端的情状值。用于第二方采用制止CSPAJEROF攻击,成功授权后回调时会原样带回。
qqLoginUrl.append(“&state=javaSdk-code”);

// 用于体现的体制。不传则私下认可突显为为PC下的体裁。
// 就算传入“mobile”,则显示为mobile端下的体裁。
qqLoginUrl.append(“&display=”);
LOG.info(“build QQLoginUrl:” + qqLoginUrl.toString());
return qqLoginUrl.toString();
}

/**
* 获取请求access token 的URubiconL第3步流程
* @param authorizationCode
* @param callBackPage
* @return
*/
public String getQQAccessTokenUrl(String authorizationCode) {

StringBuilder accessTokenUrl = new StringBuilder();

// 通过Authorization Code获取Access Token 的URl
accessTokenUrl.append(this.accessTokenUrl);

// QQ登入地点 用于获取Authorization Code
accessTokenUrl.append(“?grant_type=authorization_code”);

// 申请QQ登六成功后,分配给接纳的appid
accessTokenUrl.append(“&client_id=” + this.appKey);

// 申请QQ登十分之六功后,分配给网站的appkey
accessTokenUrl.append(“&client_secret=” + this.appSecret);

// 登入成功后赶回的authorization code
accessTokenUrl.append(“&code=” + authorizationCode);

//
client端的景况值。用于第3方应用防止CS奥迪Q3F攻击,成功授权后回调时会原样带回。
accessTokenUrl.append(“&state=javaSdk-token”);

// 成功授权后的回调地址,建议安装为网址首页或网址的用户主旨。
accessTokenUrl.append(“&redirect_uri=” + qqUnionLoginCallbackPath);

return accessTokenUrl.toString();
}

/**
* 刷新access token 的URL
* @param authorizationCode
* @param callBackPage
* @return
*/
public String refreshQQAccessTokenUrl(String refresToken) {

StringBuilder refresTokenUrl = new StringBuilder();

//刷新access token 的URL
refresTokenUrl.append(this.accessTokenUrl);

// 刷新access token 的标志
refresTokenUrl.append(“?grant_type=refresh_token”);

// 申请QQ登陆成功后,分配给使用的appid
refresTokenUrl.append(“&client_id=” + this.appKey);

// 申请QQ登六成功后,分配给网站的appkey
refresTokenUrl.append(“&client_secret=” + this.appSecret);

// 返回的refresToken
refresTokenUrl.append(“&refresh_token=” + refresToken);

return refresTokenUrl.toString();
}

/**
* 获取请求open id的UPRADOL,open id就是QQ第一方用户ID,第二步流程
* @param accessToken
* @return
*/
public String getQQOpenIdUrl(String accessToken) {

// 换取OpenId的URL
StringBuilder openIdUrl = new StringBuilder();

// 使用Access Token来获取用户的OpenID 的U奥迪Q7l
openIdUrl.append(this.openIdUrl);

// ACCESS_TOKEN
openIdUrl.append(“?access_token=” + accessToken);

return openIdUrl.toString();
}

/**
* 动态拼接获取用户数据的url 第伍部流程,获取用户的小名
* @param accessToken
* @param openId
* @return
*/
public String getQQUserInfoUrl(String accessToken, String openId) {

// 动态拼接获取用户数量的url
StringBuilder userInfoUrl = new StringBuilder();

// 获取用户数量接口的ULX570l
userInfoUrl.append(this.userInfoUrl);

// 应用的appid
userInfoUrl.append(“?oauth_consumer_key=” + this.appKey);

// 应用的accessToken
userInfoUrl.append(“&access_token=” + accessToken);

// 应用的OpenID
userInfoUrl.append(“&openid=” + openId);

return userInfoUrl.toString();
}

/**
* 用 authorizationCode 换取 AccessToken
*
* @param authorizationCode 换取accessToken的code
* @return AccessToken
* @throws IOException
*/
public String getQQAccessToken(String code) throws IOException {

String accessTokenUrl = getQQAccessTokenUrl(code);
LOG.info(“access_token init:” + accessTokenUrl);
String accessToken = “”;
String expires_in = “”;
String refresh_token = “”;

// 接受再次回到的字符串 包罗accessToken
String tempStr = “”;

// 请求QQ接口,回去重临数据
tempStr = doGet(accessTokenUrl);

LOG.info(“access_token response:” + tempStr);
// 获取accessToken退步的场子
if (tempStr.indexOf(“access_token”) >= 0) {
accessToken = tempStr.split(“&”)[0].split(“=”)[1];
expires_in = tempStr.split(“&”)[1].split(“=”)[1];
refresh_token = tempStr.split(“&”)[2].split(“=”)[1];

//token失效则再一次赚取
if(!StringUtil.isNumber(expires_in)){
accessToken = refreshQQAccessToken(refresh_token);
}
LOG.info(“access_token:” + accessToken);
return accessToken;
} else {
LOG.info(“access_token get fail return:” + tempStr);
return “”;
}
}

/**
* 用 refreshToken 刷新 AccessToken
*
* @param refreshToken
* @return AccessToken
* @throws IOException
*/
public String refreshQQAccessToken(String refreshToken) throws
IOException {

LOG.info(“refresh_access_token init:” + refreshToken);
String refreshTokenUrl = refreshQQAccessTokenUrl(refreshToken);
String accessToken = “”;
String expires_in = “”;

// 接受重回的字符串 包括accessToken
String tempStr = “”;

LOG.info(“refresh_access_token url:” + refreshToken);
// 请求QQ接口,回去重返数据
tempStr = doGet(refreshTokenUrl);

LOG.info(“refresh_access_token response:” + refreshToken);
// 获取accessToken失利的场所
if (tempStr.indexOf(“access_token”) >= 0) {
accessToken = tempStr.split(“&”)[0].split(“=”)[1];
expires_in = tempStr.split(“&”)[1].split(“=”)[1];

if(!StringUtil.isNumber(expires_in)){
accessToken = “”;
}
LOG.info(“refresh_access_token:” + accessToken);
return accessToken;
} else {
LOG.info(“refresh_access_token get fail return:” + tempStr);
return “”;
}
}

/**
* 根据AccessToken获取OpenId
*
* @param accessToken AccessToken
* @return OpenId
* @throws JsonMappingException
* @throws JsonParseException
* @throws IOException
* @throws JSONException
*/
@SuppressWarnings(“unchecked”)
public String getQQOpenId(String accessToken) throws IOException{

// 获取OpenId
String openId = “”;
String getQQOpenIdUrl = getQQOpenIdUrl(accessToken);

LOG.info(“refresh_access_token init:” + getQQOpenIdUrl);
// 请求QQ接口,回去重回数据
String interfaceData = doGet(getQQOpenIdUrl);
interfaceData =
interfaceData.substring(interfaceData.indexOf(“{“),interfaceData.indexOf(“}”)

  • 1);
    LOG.info(“get openid response:” + interfaceData);
    try {
    Map<String, String> map = JsonUtils.json2Object(interfaceData,
    HashMap.class);
    LOG.info(“get openid response to map:” + StringUtil.printParam(map));
    if(map.get(“openid”)!=null){
    openId = map.get(“openid”);
    LOG.info(“openid:” + openId);
    }
    } catch (Exception e) {
    LOG.info(“get QQ openid erro:” + e.getMessage());
    }
    return openId;
    }

@SuppressWarnings(“unchecked”)
public String getUserNickName(String accessToken, String openId) throws
IOException {

String getNickNameUrl = getQQUserInfoUrl(accessToken, openId);
LOG.info(“get nickname init:” + getNickNameUrl);
// 获取接口重返的数额
String interfaceData = doGet(getNickNameUrl);
String nickName = “”;
LOG.info(“get nickname response:” + interfaceData);

try {
Map<String, String> map = JsonUtils.json2Object(interfaceData,
HashMap.class);
if(map.get(“nickname”)!=null){
// 昵称
nickName = map.get(“nickname”);
LOG.info(“get nickname:” + nickName);
}
} catch (Exception e) {
LOG.info(“get QQ nickName erro:” + e.getMessage());
}
return nickName;
}

/**
* 链接QQ服务接口
*
* @param interfaceUrl
* 接口URL
*
* @return 接口重返的数量
* @throws IOException
*/
public String doGet(String interfaceUrl) throws IOException {
// 打字与印刷日志
LOG.info(“QQ unionLogun doGet:” + interfaceUrl);

String interfaceData = “”;
try
{
HttpResponseWrapper httpResponseWrapper =
HttpsUtil.requestGetResponse(interfaceUrl);
int state = httpResponseWrapper.getStatusCode();

// 打字与印刷日志
LOG.info(“QQ unionLogun doGet request Code:” + state);

// 是或不是请求符合规律
if (HttpsUtil.isCallOK(state)) {

// 获取重回的数据流
BufferedReader input = new BufferedReader(new
InputStreamReader(httpResponseWrapper.getResponseStream(),”UTF-8″));
String tempStr = “”;

// 获取再次回到的内容
while ((tempStr = input.readLine()) != null) {
interfaceData += tempStr.replace(“\t”, “”);
}
}
// 关闭连接
httpResponseWrapper.close();
}
catch(Exception ex)
{
LOG.error(ex,ex);
}
// 打字与印刷日志
LOG.info(“QQ unionLogun doGet return json:” + interfaceData);

return interfaceData;
}

/** *
unionLoginCallbackPath */ @Value(“${QQ_UNION_LOGIN_CALLBACK_PATH}”)
private String qqUnionLoginCallbackPath; /** * app…

Message msg = Message.obtain();

前言:

首先必须申请,必须公司,个体育工作商行,媒体等报名地址 

 private Log log = LogFactory.getLog(getClass());
 public void initWebClient(String proxyHost, int proxyPort){
  this.initWebClient();
  if(webClient != null && !StringUtils.isEmpty(proxyHost)){
   HttpHost proxy = new HttpHost(proxyHost, proxyPort);
   webClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
proxy);
  }
 }

}

微信登录类

class WechatLogin {

    private $app_id = ‘申请到的应用程式ID’; //appid

    private $app_secret = ‘申请到的SECRET’; //secret

    private $redirect_uri = ‘担任接收的地点’; //回调地址

  static public $instance;

    static public function getinstance(){

        if(!self::$instance) self::$instance = new self();

        return self::$instance;

}

    /**

    * 获取微信授权链接

    *

    * @param string $redirect_uri 跳转地址

    * @param mixed $state 随机串防CSLacrosseF攻击

    */

    public function get_authorize_url($state)

{

        //编码URL字符串

        $redirect_uri = urlencode($this->redirect_uri);

        return 
” 
           
{$redirect_uri}&response_type=code&scope=snsapi_login&state={$state}#wechat_redirect”;

  }

    /**

    * 获取授权token

*

    * @param string $code 通过get_authorize_url获取到的code

*/

    public function get_access_token($code)

{

        $token_url =
” 
    {$code}&grant_type=authorization_code”;

        $token_data = $this->http($token_url);

        if($token_data[0] == 200)

{

            return json_decode($token_data[1], TRUE);

}

        return FALSE;

}

    /**

    * 获取授权后的微信用户消息

    *

    * @param string $access_token

    * @param string $open_id

    */

    public function get_user_info($access_token,$open_id)

{

        if($access_token && $open_id)

{

            $info_url =
“”;

            $info_data = $this->http($info_url);

            if($info_data[0] == 200)

{

                return json_decode($info_data[1], TRUE);

  }

  }

        return FALSE;

  }

  public function http($url, $method = ‘GET’, $postfields = null,
$headers = array(), $debug = false)

    {

        $ci = curl_init();

        /* Curl settings */

        curl_setopt($ci, CURLOPT_HTTP_VERSION,
CURL_HTTP_VERSION_1_1);

        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);

        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);

        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ci, CURLOPT_TIMEOUT, 30);

        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);

        switch ($method) {

            case ‘POST’:

                curl_setopt($ci, CURLOPT_POST, true);

                if (!empty($postfields)) {

                    curl_setopt($ci, CURLOPT_POSTFIELDS,
$postfields);

                    $this->postdata = $postfields;

      }

                break;

      }

        curl_setopt($ci, CURLOPT_URL, $url);

        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($ci, CURLINFO_HEADER_OUT, true);

        $response = curl_exec($ci);

        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);

        if ($debug) {

            echo “=====post data======\r\n”;

            var_dump($postfields);

            echo ‘=====info=====’ . “\r\n”;

            print_r(curl_getinfo($ci));

            echo ‘=====$response=====’ . “\r\n”;

            print_r($response);

    }

        curl_close($ci);

        return array($http_code, $response);

      }

}

 /**
  * @desc 初阶化创造 WebClient
  */
 public void initWebClient() {
  log.info(“initWebClient start….”);
  try {
   PoolingClientConnectionManager tcm = new
PoolingClientConnectionManager();
   tcm.setMaxTotal(10);
   SSLContext ctx = SSLContext.getInstance(“TLS”);
   X509TrustManager tm = new X509TrustManager() {

}

工作逻辑案例:

1:登陆

金沙澳门官网7817网址 1

——–wx_state:放CSRF攻击,保存在session中

二:回调解和管理理

金沙澳门官网7817网址 2

金沙澳门官网7817网址 3

金沙澳门官网7817网址 4

微信公众号:Allen网络专业室

  • “}”);
       String url = MessageFormat.format(this.getTokenUrl, appid, secret);
       String response = executeHttpGet(url);
       accessToken = JsonUtils.read(response, “access_token”);
      } catch (Exception e) {
       log.error(“get access toekn exception”, e);
      }
      return accessToken;
     }
     /**
      * @desc 推送新闻
      * @param token
      * @param msg
      * @return
      */
     public String sendMessage(String token,String msg){
      try{
       log.info(“sendMessage start.token:”+token+”,msg:”+msg);
       String url = MessageFormat.format(this.sendMsgUrl, token);
       HttpPost post = new HttpPost(url);
       ResponseHandler<?> responseHandler = new
    BasicResponseHandler();
       StringEntity entity = new StringEntity(msg);
       post.setEntity(entity);
       String response = (String) this.webClient.execute(post,
    responseHandler);
       log.info(“return response=====start======”);
       log.info(response);
       log.info(“return response=====end======”);
       return response;

import com.tencent.mm.sdk.openapi.SendAuth;

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

* 获取openid accessToken值用于后期操作

    }

public void onResponse(Call call, Response response) throws IOException
{

    }

run(url);

 /**
  * @desc 获取授权token
  * @param appid
  * @param secret
  * @return
  */
 public String getAccessToken(String appid, String secret) {
  String accessToken = null;
  try {
   log.info(“getAccessToken start.{appid=” + appid + “,secret:” + secret

import okhttp3.Request;

public class WeixinAPIHelper {
 /**
  * 获取token接口
  */
 private String getTokenUrl =
“”;
 /**
  * 拉微信用户音讯接口
  */
 private String getUserInfoUrl =
“”;
 /**
  * 主动推送音讯接口
  */
 private String sendMsgUrl =
“”;

//用户新闻

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

import org.json.JSONObject;

1.拉取access_token
二.拉取用户音信
三.积极推送音讯
4.接口貌似要申请权限
5.依赖httpclient4.2.3 和jackson 2.2.1

finish();

    public X509Certificate[] getAcceptedIssuers() {
     return null;
    }
   };
   ctx.init(null, new X509TrustManager[] { tm }, null);
   SSLSocketFactory ssf = new SSLSocketFactory(ctx,
SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
   Scheme sch = new Scheme(“https”, 443, ssf);
   tcm.getSchemeRegistry().register(sch);
   webClient = new DefaultHttpClient(tcm);
  } catch (Exception ex) {
   log.error(“initWebClient exception”, ex);
  } finally {
   log.info(“initWebClient end….”);
  }
 }

passWord = f2_editText2.getText().toString();

复制代码 代码如下:

@Override

  }catch (Exception e) {
   log.error(“get user info exception”, e);
   return null;
  } 
 }
 /**
  * @desc 拉取用户消息
  * @param token
  * @param openid
  * @return
  */
 public WeixinOpenUser getUserInfo(String token, String openid) {
  try {
   log.info(“getUserInfo start.{token:” + token + “,openid:” + openid +
“}”);
   String url = MessageFormat.format(this.getUserInfoUrl, token,
openid);
   String response = executeHttpGet(url);
   JsonNode json = JsonUtils.read(response);
   if (json.get(“openid”) != null) {
    WeixinOpenUser user = new WeixinOpenUser();
    user.setOpenUserId(json.get(“openid”).asText());
    user.setState(json.get(“subscribe”).asText());
    if (“1”.equals(user.getState())) {
     user.setUserName(json.get(“nickname”).asText());
     user.setSex(json.get(“sex”).asText());
     user.setCity(json.get(“city”).asText());
     user.setLanguage(json.get(“language”).asText());
    }
    return user;
   }
  } catch (Exception e) {
   log.error(“get user info exception”, e);
  }
  return null;
 }
 /**
  * @desc 发起HTTP GET请求重临数据
  * @param url
  * @return
  * @throws IOException
  * @throws ClientProtocolException
  */
 private String executeHttpGet(String url) throws IOException,
ClientProtocolException {
  ResponseHandler<?> responseHandler = new
BasicResponseHandler();
  String response = (String) this.webClient.execute(new HttpGet(url),
responseHandler);
  log.info(“return response=====start======”);
  log.info(response);
  log.info(“return response=====end======”);
  return response;
 }
}

String url = “”

 private HttpClient webClient;

}

public void onResponse(Call call, Response response) throws IOException
{

//
headurl.setText(PrefUtils.getString(App.getContext(),”headurl”,null));

Request requst = new Request.Builder()

import android.graphics.BitmapFactory;

if (sendResp != null) {

} catch (JSONException e) {

} else

getUserMesg(access_token, openid);

PrefUtils.setInt(App.getContext(), “usersex”, sex);

import com.tencent.mm.sdk.openapi.BaseReq;

LogUtil.i(TAG, “getUserMesg 获得了用户Wx基本音信:”);

e.printStackTrace();

String openid = jsonObject.getString(“openid”);

/**

+ “&openid=”

}

protected void onCreate(@Nullable Bundle savedInstanceState) {

*

String responseStr = response.body().string();

super.onNewIntent(intent);

}.start();

openid.setText(PrefUtils.getString(App.getContext(), “openid”, null));

//.url(“”)

finish();

public void onResume() {

/**

}

break;

case BaseResp.ErrCode.ERR_AUTH_DENIED:

break;

msg.what = SUCCESS;

private String GetCodeRequest =
“”;

switch (resp.errCode) {

@Override

public String userName;

}

+ code

WXLogin();

});

result = “发送裁撤”;

import java.io.IOException;

private void initview() {

} else {

Toast.makeText(this, result, Toast.LENGTH_LONG).show();

// 获取用户个人消息

import okhttp3.Callback;

private TextView openid;

+ WX_APP_ID

}

userName = f2_editText1.getText().toString();

* 获取微信的个人新闻

switch (v.getId()) {

iv_qq_login = (ImageView) findViewById(R.id.iv_qq_login);

//将您接到的intent和贯彻IWXAPI伊芙ntHandler接口的目的传递给handleIntent方法

import android.widget.EditText;

if (userTag) {

private Bitmap bitmap;

/**

public void run() {

default:

Toast.makeText(App.getContext(), “请求超时”,
Toast.LENGTH_SHORT).show();

@Override

import android.widget.FrameLayout;

*/

flwx_user = (FrameLayout) findViewById(R.id.flwx_user);

OkHttpClient uOkHttpClient = new OkHttpClient();

}

String access_token =
jsonObject.getString(“access_token”).toString().trim();

LogUtil.i(TAG, “性别.. nickname:” + sex);

//todo:不使用eventbus

int sex = Integer.parseInt(jsonObject.get(“sex”).toString());//性别

SendAuth.Req req;

//finish();

// finish();

String openid = jsonObject.getString(“openid”).toString().trim();

* @param openid

}

*/

.url(url)