发表于: 2018-01-23 21:44:14
1 670
今天完成的事情:
今天遇见了新的风暴:
配置报错了,疯狂报错。
自己新写了微信的api来获取用户信息。
public class WechatUtil {
private static final String appid="";
private static final String appsecret="";
@Autowired
UsersService usersService;
public static JSONObject getOpenInfo(String url)throws Exception{
StringBuffer buffer = new StringBuffer();
// String url ="https://api.weixin.qq.com/sns/oauth2/access_token?" +
// "appid="+appid+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
URL urlConnection = new URL(url);
HttpURLConnection httpUrlConn =(HttpURLConnection)urlConnection.openConnection();
httpUrlConn.setRequestMethod("GET");
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
//关闭资源
bufferedReader.close();
inputStreamReader.close();
//释放资源
inputStream.close();
httpUrlConn.disconnect();
return JSONObject.fromObject(buffer.toString());
}
//获取用户ID
@RequestMapping(value = " /a/register",method = RequestMethod.GET)
public Long getId(HttpServletRequest request, HttpSession session){
String code = request.getParameter("code");
String url ="https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid="+appid+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
try{
JSONObject jsonObject = WechatUtil.getOpenInfo(url);
String access_token =(String)jsonObject.get("access_token");
String openid =(String)jsonObject.get("openid");
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql:///academy_karazhan?characterEncoding=UTF-8",
"root", "1234");
String sql = "select * from users where openid = ? ";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,openid);
ResultSet rs = preparedStatement.executeQuery();
if(rs.next()){
if(rs.getInt("status")==1){
return 0L;
}else {
Long id = rs.getLong("id");
session.setAttribute("id",id);
return id;
}
}else {
url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
jsonObject = WechatUtil.getOpenInfo(url);
Users users = new Users();
users.setOpenid(openid);
users.setImage((String)jsonObject.get("headimgurl"));
users.setAddress((String)jsonObject.get("province")+
(String)jsonObject.get("city")+(String)jsonObject.get("country"));
Long id = usersService.insert(users);
session.setAttribute("id",id);
return id;
}
}catch (Exception e){
e.printStackTrace();
}
return 0L;
}
}
明天计划的事情:
代码部署服务器
遇到的问题:
不能部署到服务器
收获:
对服务器更熟悉
评论