(line = in.readLine() )!= null 注意事项

(line = in.readLine() )!= null

那么我们用while((str = reader.readLine()) != null)进行读取呢,readLine是一个阻塞的方法,只要没有断开连接,就会一直等待,直到有东西返回,那么什么时候返回空呢,只有读到数据流最末尾,才返回null ,举例如,一般只有在读到文件末尾时才会是空,至于读取服务器端的数据,一般不会是空,那么有时候我们采用特定的字符来代表结束,在网络上,一直等待输入,即使是对方什么也不输入
,只是回车,readline也不会返回null,如果I/O中断,会返回I/O异常,还是不会返回null 除非你使用的数据流有固定长度(比如文件数据流,或者ByteArrayInputStream之类),而不是网络数据流(阻塞模式)。

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
A: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Map; public class WeChatHelper { private static final String APP_ID = "Your_App_ID"; // 你的微信应用ID private static final String APP_SECRET = "Your_App_Secret"; // 你的微信应用秘钥 /** * 获取微信用户的手机号 * @param code 微信用户登录后获取到的code * @return 手机号 */ public static String getPhoneNumber(String code) { StringBuilder sb = new StringBuilder(); try { // 获取access_token String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+APP_ID+"&secret="+APP_SECRET+"&code="+code+"&grant_type=authorization_code"; URL url = new URL(accessTokenUrl); URLConnection conn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); Map<String,String> tokenMap = JSON.parseObject(sb.toString(), new TypeReference<Map<String, String>>(){}); // 获取用户信息 String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+tokenMap.get("access_token")+"&openid="+tokenMap.get("openid")+"&lang=zh_CN"; url = new URL(userInfoUrl); conn = url.openConnection(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); while ((line = in.readLine()) != null) { sb.append(line); } in.close(); Map<String,String> userMap = JSON.parseObject(sb.toString(), new TypeReference<Map<String, String>>(){}); // 返回手机号 return userMap.get("phone_number"); } catch (Exception e) { e.printStackTrace(); return ""; } } } ``` 使用方法: ```java String code = "xxxxxxxxxxxxxxxxxxxxx"; // 微信用户登录后获取到的code String phoneNumber = WeChatHelper.getPhoneNumber(code); // 获取用户手机号 ``` 注意事项: - 需要引入fastjson依赖; - 需要替换APP_ID和APP_SECRET变量为你自己的微信应用ID和秘钥; - 需要在微信开放平台设置授权回调域名,并将域名添加到小程序配置文件中。 - 需要在小程序端使用wx.login()方法获取用户登录的code。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值