使用HttpClient发送https请求

项目中需要用到HttpClient去网站请求数据,连接需要使用https方式。参考网上的各种资料,我的实现步骤如下:

 

1. 使用浏览器访问网站,导出网站的证书。

2. 我使用的是jdk1.7,内含jre1.7。我在jdk1.7/bin目录中执行:

keytool -import -keystore "my-jdk-jre-root/lib/security/cacerts" -storepass changeit -keypass changeit -alias myalias -file cert-file.cer

将证书导入jdk自带的jre的cacerts证书库。

3. 建立工程,创建如下代码。工程的JRE System Library使用jdk1.7自带的jre,也就是刚才导入证书的jre。

......

public static void main(String args[]){

        HttpClient httpClient = new HttpClient();

Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");

httpClient.getState().setCredentials(new AuthScope("https://url", 80, AuthScope.ANY_REALM), defaultcreds);

GetMethod getMethod = new GetMethod("http://url");

int state = httpClient.executeMethod(getMethod);

System.out.println("response=" + getMethod.getResponseBodyAsString());

getMethod.releaseConnection();

}

......

 

代码执行成功,成功登录网站。需要注意的是,这种方式可能导致帐号和密码泄露。

 

你可能感兴趣的:(httpclient)