//授权
wx.login({
success: function (res) {
console.log('login:code', res.code)
//发送请求
wx.request({
url: '你自己的接口名字', //接口地址
data: {
'code': res.code
},
header: {
'content-type': 'application/json'
},
success: function (res) {
console.log("record 成功", res.data)
if (res.error) { //发生错误
console.log("错误:", res.msg);
} else { //返回成功
try {
wx.setStorageSync('openId', res.data.openid) // 全局赋值
openid = wx.getStorageSync("openId"); // 取值
} catch (e) {
console.log("wx.login 错误", e);
}
}
},
fail: function (err) {
console.log("record 失败", err);
}
})
}
})
后台接口:
@RequestMapping("httpClient")
public void httpWechat(HttpServletRequest request,
HttpServletResponse response) throws IOException {
String appId = "你的小程序APPID";
String appSecret = "你的小程序APPSECRET";
String code = request.getParameter("code");
URL url = new URL("https://api.weixin.qq.com/sns/jscode2session?appid="
+ appId + "&secret=" + appSecret
+ "&grant_type=authorization_code&js_code=" + code);
String resp = HTTPUtils.get(url);
Writer out = response.getWriter();
out.write(resp);
out.flush();
}
import java.io.IOException;
import java.net.URL;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
public class HTTPUtils {
private final static Logger logger = LogManager.getLogger(HTTPUtils.class);
private final static String OPERATER_NAME = "【HTTP操作】";
private final static int SUCCESS = 200;
private final static String UTF8 = "UTF-8";
private HttpClient client;
private static HTTPUtils instance = new HTTPUtils();
/**
* 私有化构造器
*/
private HTTPUtils() {
HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = httpConnectionManager.getParams();
params.setConnectionTimeout(5000);
params.setSoTimeout(20000);
params.setDefaultMaxConnectionsPerHost(1000);
params.setMaxTotalConnections(1000);
client = new HttpClient(httpConnectionManager);
client.getParams().setContentCharset(UTF8);
client.getParams().setHttpElementCharset(UTF8);
}
/**
* get请求
*/
public static String get(URL url) {
return instance.doGet(url);
}
private String doGet(URL url) {
long beginTime = System.currentTimeMillis();
String respStr = StringUtils.EMPTY;
try {
System.out.println(OPERATER_NAME + "开始get通信,目标host:" + url);
HttpMethod method = new GetMethod(url.toString());
// 中文转码
method.getParams().setContentCharset(UTF8);
try {
client.executeMethod(method);
} catch (HttpException e) {
// logger.error(new StringBuffer("发送HTTP GET给\r\n").append(url)
// .append("\r\nHTTP异常\r\n"), e);
} catch (IOException e) {
// logger.error(new StringBuffer("发送HTTP GET给\r\n").append(url)
// .append("\r\nIO异常\r\n"), e);
}
if (method.getStatusCode() == SUCCESS) {
respStr = method.getResponseBodyAsString();
}
// 释放连接
method.releaseConnection();
System.out.println(OPERATER_NAME + "通讯完成,返回码:"
+ method.getStatusCode());
System.out.println(OPERATER_NAME + "返回内容:"
+ method.getResponseBodyAsString());
System.out.println(OPERATER_NAME + "结束..返回结果:" + respStr);
} catch (Exception e) {
// System.out.println(OPERATER_NAME, e);
}
long endTime = System.currentTimeMillis();
System.out.println(OPERATER_NAME + "共计耗时:" + (endTime - beginTime)
+ "ms");
return respStr;
}
/**
* POST请求
*/
public static String post(URL url, String content) {
return instance.doPost(url, content);
}
private String doPost(URL url, String content) {
long beginTime = System.currentTimeMillis();
String respStr = StringUtils.EMPTY;
try {
System.out.println(OPERATER_NAME + "开始post通信,目标host:"
+ url.toString());
System.out.println("通信内容:" + content);
PostMethod post = new PostMethod(url.toString());
RequestEntity requestEntity = new StringRequestEntity(content,
"application/json;charse=UTF-8", UTF8);
post.setRequestEntity(requestEntity);
// 设置格式
post.getParams().setContentCharset(UTF8);
client.executeMethod(post);
if (post.getStatusCode() == SUCCESS) {
respStr = post.getResponseBodyAsString();
}
System.out.println(OPERATER_NAME + "通讯完成,返回码:"
+ post.getStatusCode());
System.out.println(OPERATER_NAME + "返回内容:"
+ post.getResponseBodyAsString());
System.out.println(OPERATER_NAME + "结束..返回结果:" + respStr);
post.releaseConnection();
} catch (Exception e) {
// logger.error(OPERATER_NAME, e);
}
long endTime = System.currentTimeMillis();
System.out.println(OPERATER_NAME + "共计耗时:" + (endTime - beginTime)
+ "ms");
return respStr;
}
最近在弄小程序 有问题随时沟通 QQ:1002909676