<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.READ_PHONE_STATE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<activity
android:name=".wxapi.WXEntryActivity"
android:label="@string/title_activity_wxlogin"
android:launchMode="singleTop"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
api.handleIntent(getIntent(), this);
package com.example.justyoung.logintest.wxapi;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.justyoung.logintest.HttpsHelper;
import com.example.justyoung.logintest.R;
import com.example.justyoung.logintest.fileExplorer.WXConstant;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
public class WXEntryActivity extends ActionBarActivity implements IWXAPIEventHandler{
private Button wxLogin;
private IWXAPI api;
private static String uuid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wxlogin);
wxLogin = (Button) findViewById(R.id.wx_login_button);
wxLogin.setOnClickListener(new WXLoginEvent());
api = WXAPIFactory.createWXAPI(this, WXConstant.APPID);
api.registerApp(WXConstant.APPID);
api.handleIntent(getIntent(), this);
}
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
api.handleIntent(intent, this);
}
@Override
public void onResp(BaseResp resp) {
String result;
switch (resp.errCode) {
case BaseResp.ErrCode.ERR_OK:
result = "OK";
SendAuth.Resp regResp = (SendAuth.Resp)resp;
if (!regResp.state.equals(uuid))
return;
String code = regResp.code;
new WXLoginThread("https://192.168.2.133:8443/CloudStorageServer/wechat/login?code=" + code).start();
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
result = "USER_CANCEL";
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
result = "ERR_AUTH_DENIED";
break;
default:
result = "errcode_unknown";
break;
}
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
class WXLoginEvent implements View.OnClickListener {
@Override
public void onClick(View v) {
uuid = UUID.randomUUID().toString();
final SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = uuid;
api.sendReq(req);
}
}
private class WXLoginThread extends Thread {
private String url;
public WXLoginThread(String url) {
this.url = url;
}
@Override
public void run() {
HttpsHelper httpsHelper = new HttpsHelper();
try {
httpsHelper.prepareHttpsConnection(url);
String response = httpsHelper.connect();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
uuid = UUID.randomUUID().toString(); final SendAuth.Req req = new SendAuth.Req(); req.scope = "snsapi_userinfo"; req.state = uuid; api.sendReq(req);
private void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String code = getParameter(request, "code");
if (isArgumentNullOrEmpty(code)) {
Log.logger.info("code为空");
return;
}
Log.logger.info("收到code: " + code);
try {
AccessToken accessToken = new AccessToken("/sns/oauth2/access_token", "authorization_code", code);
AccessToken.UserData userData = accessToken.getMetaData().getUserInfo();
... // userData中就是我们通过access_token获取的用户信息了。
} catch (WeiXinException e) {
Log.logException(e);
writeMessage(response, e.getMessage());
return;
} catch (Exception e) {
Log.logException(e);
writeMessage(response, "login error");
return;
}
}
package com.cyber_space.thirdparty.weixin;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.cyber_space.util.JsonUtil;
public class AccessToken {
CloseableHttpClient httpClient;
HttpGet httpGet;
URI uri;
String code;
/**
* 用于公众号
*
* @throws URISyntaxException
*/
public AccessToken() throws URISyntaxException {
uri = new URIBuilder().setScheme("https").setHost("api.weixin.qq.com").setPath("/cgi-bin/token")
.setParameter("grant_type", "client_credential").setParameter("appid", WeiXinConfig.APP_ID)
.setParameter("secret", WeiXinConfig.APP_SECRET).build();
httpClient = HttpClients.createDefault();
httpGet = new HttpGet(uri);
}
public AccessToken(String path, String grantType, String code) throws URISyntaxException {
uri = new URIBuilder().setScheme("https").setHost("api.weixin.qq.com").setPath(path)
.setParameter("grant_type", grantType).setParameter("appid", WeiXinConfig.APP_ID)
.setParameter("secret", WeiXinConfig.APP_SECRET).setParameter("code", code).build();
httpClient = HttpClients.createDefault();
httpGet = new HttpGet(uri);
}
public String getAccessToken() throws ClientProtocolException, IOException {
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
HttpEntity httpEntity = response.getEntity();
if (httpEntity == null)
return null;
httpEntity = new BufferedHttpEntity(httpEntity);
String returnString = EntityUtils.toString(httpEntity);
String accessToken = com.cyber_space.util.JsonUtil.getAttribute(returnString, "access_token");
return accessToken;
} finally {
response.close();
}
}
/**
* 获得用户的元数据信息,只包括openid和access_token
*
* @return
* @throws ClientProtocolException
* @throws IOException
* @throws WeiXinException
*/
public UserData getMetaData() throws ClientProtocolException, IOException, WeiXinException {
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
HttpEntity httpEntity = response.getEntity();
if (httpEntity == null)
return null;
httpEntity = new BufferedHttpEntity(httpEntity);
String returnString = EntityUtils.toString(httpEntity);
JsonUtil jUtil = new JsonUtil(returnString, JsonUtil.JSONOBJECT);
String error = null;
try {
error = jUtil.getAttribute("errcode");
} catch (Exception e) {
}
if (error != null && !error.equals("")) {
throw new WeiXinException(WeiXinException.INVALID_OPENID);
}
String openid = jUtil.getAttribute("openid");
String accessToken = jUtil.getAttribute("access_token");
UserData uData = new UserData(openid, accessToken);
return uData;
} finally {
response.close();
}
}
public class UserData {
public String openid;
public String accessToken;
public String nickname;
public String sex;
public String province;
public String city;
public String country;
public String headimgurl;
public String privilege;
public String unionid;
public UserData(String openid, String accessToken) {
this.openid = openid;
this.accessToken = accessToken;
}
public UserData getUserInfo()
throws IOException, IllegalArgumentException, IllegalAccessException, URISyntaxException, WeiXinException {
URI uri = new URIBuilder().setScheme("https").setHost("api.weixin.qq.com").setPath("/sns/userinfo")
.setParameter("access_token", this.accessToken).setParameter("openid", this.openid).build();
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
HttpEntity httpEntity = response.getEntity();
if (httpEntity == null)
throw null;
httpEntity = new BufferedHttpEntity(httpEntity);
String jsonString = EntityUtils.toString(httpEntity);
JsonUtil jUtil = new JsonUtil(jsonString, JsonUtil.JSONOBJECT);
String errcode = null;
try {
errcode = jUtil.getAttribute("errcode");
} catch (Exception e) {
}
// 通过反射循环赋值
if (errcode == null || errcode.equals("")) {
for (Field i : getClass().getFields()) {
if (!i.getName().equals("accessToken"))
i.set(this, jUtil.getAttribute(i.getName()));
}
return this;
}
else {
throw new WeiXinException(WeiXinException.INVALID_ACCESSTOKEN);
}
} finally {
response.close();
}
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-3 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2026 源码网商城 (www.yuanmawang.com) 版权所有