之前做过一个webservie项目,需要请求 带有用户名密码校验 的https 接口。
刚开始用的就是Authenticator.setDefault 来处理用户名密码校验,但是后台客户提出一个需求,用户名与密码需要可以改变。
天真的写好代码就给客户演示了。。。然后就被这玩意坑了。。。
找了不少资料,最后结果是说 这东西是jdk 2007的bug。。。。无解,只能找其他东西替换他了。
直接上代码吧~~~
urlCon = (HttpsURLConnection) (new URL(httpsUrl)).openConnection();
//urlCon.addRequestProperty("PasswordAuthentication", "xxxxx:xxxxx");
//String users = DemoService.username+":"+DemoService.password;
//校验密码
String username = DemoService.username;
String password = DemoService.password;
String input = username + ":" + password;
//String encoding = new sun.misc.BASE64Encoder().encode(input.getBytes());
String encoding = Base64.encodeBase64String(input.getBytes());
urlCon.setRequestProperty("Authorization", "Basic " + encoding);
将Authenticator.setDefault 替换成上方的方式即可,用户名密码 修改 立刻生效。
这个故事告诉我们 ,再简单的代码 也需要好好测试啊