rest接口调用

/**
* 心得:一定要关闭流,inStream
* 那也就是用变量接收文件中的值
* @author Administrator
*
*/
public class HttpClientDemo {

private String trustStore = "证书名";
private String keyStorePwd = "pwd";

public void start(){
InputStream inStream = null;

try {
//加载配置文件
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("路径/rest.properties");
inStream = new BufferedInputStream(fis);
prop.load(inStream);

//加载安全证书
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(ClassLoader.getSystemResourceAsStream(trustStore),keyStorePwd.toCharArray());

//SSL:一种保证网络上的恋歌节点进行安全通信的协议
//连接采用tls还是ssl的安全方式
SSLContext sslContext = SSLContext.getInstance("TLS");

X509TrustManager tm = new X509TrustManager(){

@Override
public void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {}

@Override
public void checkServerTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {}

@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}

};

KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks,"pwd".toCharArray());

sslContext.init(kmf.getKeyManagers(), new TrustManager[]{tm}, new SecureRandom());

SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

String url = String.format("https://%s:%s%s", prop.getProperty("ip"),
prop.getProperty("port"),
prop.getProperty("url"));

JSONObject json = new JSONObject();
json.put("param",prop.getProperty("param"));

HttpClient httpClient = new DefaultHttpClient();
//443  https的默认端口号
httpClient.getConnectionManager().getSchemeRegistry().registry().register(new Scheme("https",443,socketFactory));

HttpPost hp = new HttpPost(url);
hp.setHeader("Context-Type","application/json;charset=UTF-8");
hp.setHeader("Accept","application/json;charset=UTF-8");
hp.setEntity(new StringEntity(json.toString()));

HttpResponse httpResponse = httpClient.execute(hp);
HttpEntity entity = hp.getEntity();
httpResponse.getStatusLine().getStatusCode();
EntityUtils.toString(entity,"UTF-8");

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
finally{
if(null != inStream){
inStream.close();
inStream = null;
}
}

}



}
get,put,delete,post等方法,使用同上

代码中用的证书下次再写,怎么查看证书,内容

猜你喜欢

转载自1282084618.iteye.com/blog/2234772
今日推荐