A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© BlackHorse001 中级黑马   /  2015-9-5 08:42  /  227 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

java模拟https登陆

首先我要登陆,然后保存cookie,然后利用cookie来访问后续的网页,发包,处理包这样,然后,为了方便,我选择了 org.apache.http 这个库,典型的一个登陆场景应该是这样的,以后遇到问题一定先要去看官方的例子,别人给出的例子一般要么是不能用,要么是用的方法都是一些过时的,虽然能用,但看到警告还是不舒服。

public static BasicCookieStore cookieStore;
//整个过程用一个client
public static CloseableHttpClient httpclient;
cookieStore = new BasicCookieStore();
httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
//先访问一下首页,然后cookie、会填充进来
HttpGet httpget = new HttpGet(“https://leaver.me/index.htm“);
httpclient.execute(httpget);
CloseableHttpResponse responseCookie = null;
//然后post请求登陆
HttpPost httpost = new HttpPost(“https://leaver.me/login.htm“);
//通过键值对来作为post参数
List < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > (1);
nameValuePairs.add(new BasicNameValuePair(“loginType”, “1”));
nameValuePairs.add(new BasicNameValuePair(“loginName”, username));
nameValuePairs.add(new BasicNameValuePair(“Password”, password));
httpost.setEntity(new UrlEncodedFormEntity(nameValuePairs, Consts.UTF_8));
CloseableHttpResponse responLogin = null;
responLogin = httpclient.execute(httpost);


但是,这个过程报了如下的错

e: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

google之,发现时访问https的原因。需要先安装对应站点的证书。这里要用到一个通用的java类,我贴下链接

编译这个工具类,然后执行java InstallCert <host>[:port] 会生成一个证书文件

然后在项目里通过

System.setProperty(“javax.net.ssl.trustStore”,
                “证书路径”);


设置即可,你可以吧证书文件放到资源目录,就更好了。

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马