java调用https
❶ java怎样调用https类型的webservice
输入<Server>的主密码
(如果和 keystore 密码相同,按回车):
以上命令执行完成后,将获得一个名为server.keystore的密匙库。
生成客户端的信任库。首先输出RSA证书:
keytool -export -alias Server -file test_axis.cer -storepass strongit-keystore server.keystore
然后把RSA证书输入到一个新的信任库文件中。这个信任库被客户端使用,被用来验证服务器端的身份。
keytool -import -file test_axis.cer -storepass changeit -keystore client.truststore -alias serverkey -noprompt
以上命令执行完成后,将获得一个名为client.truststore的信任库。
同理生成客户端的密匙库client.keystore和服务器端的信任库server.truststore.方便起见给出.bat文件
gen-cer-store.bat内容如下:
更改Tomcat的配置文件(server.xml),增加以下部署描述符:(其实里面有,只是被注释掉了)
1 <Connector port="8440"
2 maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
3 enableLookups="false" disableUploadTimeout="true"
4 acceptCount="100" scheme="https" secure="true"
5 clientAuth="true" keystoreFile="f:\server.keystore" keystorePass="changeit"
6 truststoreFile="f:\server.truststore" truststorePass="changeit"
7 sslProtocol="TLS" />
❷ java怎么调用https外部接口
方法:只要New一个Map,然后把要传递的参数以键值对的形式存入Map即可。privatevoidExample(){Stringurl=地址;Mapparam=newHashMap();p.put("ParamName","ParamValue");Stringhtml=this.visitURL(url,param);}
❸ 如何在java中发起http和https请求
1.写http请求方法
[java] view plain
//处理http请求 requestUrl为请求地址 requestMethod请求方式,值为"GET"或"POST"
public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
StringBuffer buffer=null;
try{
URL url=new URL(requestUrl);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod(requestMethod);
conn.connect();
//往服务器端写内容 也就是发起http请求需要带的参数
if(null!=outputStr){
OutputStream os=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//读取服务器端返回的内容
InputStream is=conn.getInputStream();
InputStreamReader isr=new InputStreamReader(is,"utf-8");
BufferedReader br=new BufferedReader(isr);
buffer=new StringBuffer();
String line=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}
return buffer.toString();
}
❹ 用java调用https webservice,该怎么处理
publicStringsendPost(Stringurl,Stringparam){
StringrequestData=param;//参数
StringrequsetString=url;//远程接口地址
//'tcare.
//信任任何证书
X509TrustManagertrustManager=newX509TrustManager(){
publicvoidcheckClientTrusted(X509Certificate[]chain,StringauthType)throwsCertificateException{
//Don'tdoanything.
}
publicvoidcheckServerTrusted(X509Certificate[]chain,StringauthType)throwsCertificateException{
//Don'tdoanything.
}
publicX509Certificate[]getAcceptedIssuers(){
//Don'tdoanything.
returnnull;
}
};
//把信任证书放到ssl中
SSLContextsslcontext;
Stringresult="";
try{
sslcontext=SSLContext.getInstance("SSL");
sslcontext.init(null,newTrustManager[]{trustManager},null);
//
//(
//,amethodwhichdoesn't
//existanywhereIcanfind,buthey-ho).
SSLSocketFactorysf=newSSLSocketFactory(sslcontext);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
DefaultHttpClienthttpclient=newDefaultHttpClient();
httpclient.getConnectionManager().getSchemeRegistry().register(newScheme("https",sf,VariableTool.HTTP_NUM));
HttpPosthttpPost=newHttpPost(requsetString);
//执行https请求
httpPost.setHeader("Authorization","basic"+"dGNsb3VkYWRtaW46dGNsb3VkMTIz");
httpPost.setHeader("Content-type","application/xml");
StringEntityreqEntity;
//将请求参数封装成HttpEntity
reqEntity=newStringEntity(requestData,"UTF-8");
BufferedHttpEntitybhe=newBufferedHttpEntity(reqEntity);
httpPost.setEntity(bhe);
HttpResponseresponse=httpclient.execute(httpPost);
HttpEntityresEntity=response.getEntity();
InputStreamReaderreader=newInputStreamReader(resEntity.getContent());
char[]buff=newchar[1024];
intlength=0;
while((length=reader.read(buff))!=-1){
result+=newString(buff,0,length);
}
logger.debug("调用ws接口返回:"+result);
httpclient.getConnectionManager().shutdown();
}catch(Exceptione){
e.printStackTrace();
return"";
}
returnresult;
}
result就是远程接口返回的接口
❺ 怎样用java调用https接口
下面这个函数可以直接用:
public static String requsetUrl(String urls) throws Exception{
BufferedReader br = null;
String sTotalString= "";
try{
URL url = new URL(urls);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(3000);
connection.setDoOutput(true);
String line = "";
InputStream l_urlStream;
l_urlStream = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
while ((line = br.readLine()) != null) {
sTotalString += line + "\r\n";
}
} finally {
if(br!=null){
try {
br.close();
} catch (IOException e) {
br = null;
}
}
}
return sTotalString;
}
❻ java https接口调用出错
您这个明显HTTPS端口不信任或不通,请检查HTTPS链接是否可以直接正常信任访问,并且进行ATS安全标准检测,是否达到要求,相关HTTPS技术支持:网页链接
❼ JAVA怎样调用https类型的webservice
1.打开webService链接,右键属性—》证书—》详细信息—》复制到文件,保存cer格式的文件。
2. 复制下面的cmd命令,执行keytool命令,生成keystore文件,例如
c:\nciic.keystore
keytool -import -alias nciic -file c:\jswszx.cer -keystore c:\nciic.keystore
它会提示输入密码,随便输入,例如:123456,回车
4.他会提示是否信任这个认证,输入Y,回车,指定目录下就会生成nciic.keystore文件
它会提示输入密码,随便输入,例如:123456,回车
4.他会提示是否信任这个认证,输入Y,回车,指定目录下就会生成nciic.keystore文件
5.修改Java代码
在调用接口方法之前,添加如下代码:
System.setProperty("javax.NET.ssl.trustStore","c://nciic.keystore"); System.setProperty("java.protocol.handler.pkgs","com.sun.Net.ssl.internal.www.protocol");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
❽ 如何用JAVA实现HTTPS客户端
import java.io.*;
import java.net.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.*;
public class TrustSSL {
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public static void main(String[] args) throws Exception {
InputStream in = null;
OutputStream out = null;
byte[] buffer = new byte[4096];
String str_return = "";
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
new java.security.SecureRandom());
URL console = new URL(
"https://192.168.1.188/test.php?username=测试");
HttpsURLConnection conn = (HttpsURLConnection) console
.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
InputStream is = conn.getInputStream();
DataInputStream indata = new DataInputStream(is);
String ret = "";
while (ret != null) {
ret = indata.readLine();
if (ret != null && !ret.trim().equals("")) {
str_return = str_return
+ new String(ret.getBytes("ISO-8859-1"), "GBK");
}
}
conn.disconnect();
} catch (ConnectException e) {
System.out.println("ConnectException");
System.out.println(e);
throw e;
} catch (IOException e) {
System.out.println("IOException");
System.out.println(e);
throw e;
} finally {
try {
in.close();
} catch (Exception e) {
}
try {
out.close();
} catch (Exception e) {
}
}
System.out.println(str_return);
}
}
❾ JAVA怎样调用https类型的webservice
第一步按照Axis生成本地访问客户端,完成正常的webservice调用的开发,这里的细节我就不再描述,重点说明和http不同的地方-证书的生成和使用。这里假设需要访问的网址是https://www.abc.com ,那么就需要生成网址的安全证书设置到系统属性中,并且需要在调用代码前。如下图
第二步就是介绍怎样生成证书,先写一个InstallCert.java类放到自己电脑的D盘根目录下,(注意这个类是没有包名的)类中代码如下:
/**
*
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
public class InstallCert {
public static void main(String[] args) throws Exception {
String host;
int port;
char[] passphrase;
if ((args.length == 1) || (args.length == 2)) {
String[] c = args[0].split(":");
host = c[0];
port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
String p = (args.length == 1) ? "changeit" : args[1];
passphrase = p.toCharArray();
} else {
System.out
.println("Usage: java InstallCert <host>[:port] [passphrase]");
return;
}
File file = new File("jssecacerts");
if (file.isFile() == false) {
char SEP = File.separatorChar;
File dir = new File(System.getProperty("java.home") + SEP + "lib"
+ SEP + "security");
file = new File(dir, "jssecacerts");
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
System.out.println("Loading KeyStore " + file + "...");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
SSLContext context = SSLContext.getInstance("TLS");
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager) tmf
.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory factory = context.getSocketFactory();
System.out
.println("Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(10000);
try {
System.out.println("Starting SSL handshake...");
socket.startHandshake();
socket.close();
System.out.println();
System.out.println("No errors, certificate is already trusted");
} catch (SSLException e) {
System.out.println();
e.printStackTrace(System.out);
}
X509Certificate[] chain = tm.chain;
if (chain == null) {
System.out.println("Could not obtain server certificate chain");
return;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
System.out.println();
System.out.println("Server sent " + chain.length + " certificate(s):");
System.out.println();
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chain.length; i++) {
X509Certificate cert = chain[i];
System.out.println(" " + (i + 1) + " Subject "
+ cert.getSubjectDN());
System.out.println(" Issuer " + cert.getIssuerDN());
sha1.update(cert.getEncoded());
System.out.println(" sha1 " + toHexString(sha1.digest()));
md5.update(cert.getEncoded());
System.out.println(" md5 " + toHexString(md5.digest()));
System.out.println();
}
System.out
.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
String line = reader.readLine().trim();
int k;
try {
k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
} catch (NumberFormatException e) {
System.out.println("KeyStore not changed");
return;
}
X509Certificate cert = chain[k];
String alias = host + "-" + (k + 1);
ks.setCertificateEntry(alias, cert);
OutputStream out = new FileOutputStream("jssecacerts");
ks.store(out, passphrase);
out.close();
System.out.println();
System.out.println(cert);
System.out.println();
System.out
.println("Added certificate to keystore 'jssecacerts' using alias '"
+ alias + "'");
}
private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 3);
for (int b : bytes) {
b &= 0xff;
sb.append(HEXDIGITS[b >> 4]);
sb.append(HEXDIGITS[b & 15]);
sb.append(' ');
}
return sb.toString();
}
private static class SavingTrustManager implements X509TrustManager {
private final X509TrustManager tm;
private X509Certificate[] chain;
SavingTrustManager(X509TrustManager tm) {
this.tm = tm;
}
public X509Certificate[] getAcceptedIssuers() {
throw new UnsupportedOperationException();
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
throw new UnsupportedOperationException();
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
this.chain = chain;
tm.checkServerTrusted(chain, authType);
}
}
}
将上面的InstallCert.java编译成InstallCert.class文件放到自己电脑的D盘根目录下。这是正常的情况下D盘根目录下会有3个文件,如下图:
打开cmd进入到d盘开始执行生成证书命令,我这里不便于那我的网址测试我用支付宝的网址来测试的,输入:java InstallCert www.alipay.com 如下图
当出现了:Enter certificate to add to trusted keystore or 'q' to quit: [1]
这行代码时,输入1,回车。正常执行完后在D盘根目录下就会出现证书“jssecacerts”文件,具体如下图:
6
得到证书后将证书拷贝到$JAVA_HOME/jre/lib/security目录下,我这里是win7系统,在尝试的过程中需要将证书重命名为:cacerts 放进去才会有用。(这个步骤在不同的环境和操作系统下有点不同,需要注意)
❿ 如何使用JAVA请求HTTPS
1.写http请求方法
[java] view plain
//处理http请求 requestUrl为请求地址 requestMethod请求方式,值为"GET"或"POST"
public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
StringBuffer buffer=null;
try{
URL url=new URL(requestUrl);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod(requestMethod);
conn.connect();
//往服务器端写内容 也就是发起http请求需要带的参数
if(null!=outputStr){
OutputStream os=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//读取服务器端返回的内容
InputStream is=conn.getInputStream();
InputStreamReader isr=new InputStreamReader(is,"utf-8");
BufferedReader br=new BufferedReader(isr);
buffer=new StringBuffer();
String line=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}
return buffer.toString();
}
2.测试。
[java] view plain
public static void main(String[] args){
String s=httpRequest("","GET",null);
System.out.println(s);
}
输出结果为的源代码,说明请求成功。
注:1).第一个参数url需要写全地址,即前边的http必须写上,不能只写这样的。
2).第二个参数是请求方式,一般接口调用会给出URL和请求方式说明。
3).第三个参数是我们在发起请求的时候传递参数到所要请求的服务器,要传递的参数也要看接口文档确定格式,一般是封装成json或xml.
4).返回内容是String类,但是一般是有格式的json或者xml。
二:发起https请求。
1.https是对链接加了安全证书SSL的,如果服务器中没有相关链接的SSL证书,它就不能够信任那个链接,也就不会访问到了。所以我们第一步是自定义一个信任管理器。自要实现自带的X509TrustManager接口就可以了。
[java] view plain
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
注:1)需要的包都是java自带的,所以不用引入额外的包。
2.)可以看到里面的方法都是空的,当方法为空是默认为所有的链接都为安全,也就是所有的链接都能够访问到。当然这样有一定的安全风险,可以根据实际需要写入内容。
2.编写https请求方法。
[java] view plain
/*
* 处理https GET/POST请求
* 请求地址、请求方法、参数
* */
public static String httpsRequest(String requestUrl,String requestMethod,String outputStr){
StringBuffer buffer=null;
try{
//创建SSLContext
SSLContext sslContext=SSLContext.getInstance("SSL");
TrustManager[] tm={new MyX509TrustManager()};
//初始化
sslContext.init(null, tm, new java.security.SecureRandom());;
//获取SSLSocketFactory对象
SSLSocketFactory ssf=sslContext.getSocketFactory();
URL url=new URL(requestUrl);
HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
//设置当前实例使用的SSLSoctetFactory
conn.setSSLSocketFactory(ssf);
conn.connect();
//往服务器端写内容
if(null!=outputStr){
OutputStream os=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//读取服务器端返回的内容
InputStream is=conn.getInputStream();
InputStreamReader isr=new InputStreamReader(is,"utf-8");
BufferedReader br=new BufferedReader(isr);
buffer=new StringBuffer();
String line=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}
return buffer.toString();
}
可见和http访问的方法类似,只是多了SSL的相关处理。
3.测试。先用http请求的方法访问,再用https的请求方法访问,进行对比。
http访问:
[java] view plain
public static void main(String[] args){
String s=httpRequest("","GET",null);
System.out.println(s);
}
结果为:
https访问:
[java] view plain
public static void main(String[] args){
String s=httpsRequest("","GET",null);
System.out.println(s);
}
结果为:
可见https的链接一定要进行SSL的验证或者过滤之后才能够访问。
三:https的另一种访问方式——导入服务端的安全证书。
1.下载需要访问的链接所需要的安全证书。 以这个网址为例。
1)在浏览器上访问。
2)点击上图的那个打了×的锁查看证书。
3)选择复制到文件进行导出,我们把它导入到java项目所使用的jre的lib文件下的security文件夹中去,我的是这个路径。D:\Program Files (x86)\Java\jre8\lib\security
注:中间需要选导出格式,就选默认的就行,还需要命名,我命名的是12306.
2.打开cmd,进入到java项目所使用的jre的lib文件下的security目录。
3.在命令行输入 Keytool -import -alias 12306 -file 12306.cer -keystore cacerts
4.回车后会让输入口令,一般默认是changeit,输入时不显示,输入完直接按回车,会让确认是否信任该证书,输入y,就会提示导入成功。
5.导入成功后就能像请求http一样请求https了。
测试:
[java] view plain
public static void main(String[] args){
String s=httpRequest("","GET",null);
System.out.println(s);
}
结果:
现在就可以用http的方法请求https了。
注:有时候这一步还是会出错,那可能是jre的版本不对,我们右键run as——run configurations,选择证书所在的jre之后再运行。