导航:首页 > 编程语言 > java调用https

java调用https

发布时间:2022-09-13 19:32:59

java怎样调用https类型的webservice

使用JDK自带的工具创建密匙库和信任库。

1)通过使用以下的命令来创建服务器端的密匙库:
keytool -genkey -alias Server -keystore server.keystore -keyalg RSA
输入keystore密码: strongit
您的名字与姓氏是什么?
[Unknown]: Server
您的组织单位名称是什么?
[Unknown]: ec
您的组织名称是什么?
[Unknown]: ec
您所在的城市或区域名称是什么?
[Unknown]: nanchang
您所在的州或省份名称是什么?
[Unknown]: jiangxi
该单位的两字母国家代码是什么
[Unknown]: CN
CN=Server, OU=ec, O=ec, L=beijing, ST=beijing, C=CN 正确吗?
[否]: y

输入<Server>的主密码
(如果和 keystore 密码相同,按回车):
以上命令执行完成后,将获得一个名为server.keystore的密匙库。

2)生成客户端的信任库。首先输出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的信任库。

3)同理生成客户端的密匙库client.keystore和服务器端的信任库server.truststore.方便起见给出.bat文件
gen-cer-store.bat内容如下:

1 set SERVER_DN="CN=Server, OU=ec, O=ec, L=nanchang, S=jiangxi, C=CN"
2 set CLIENT_DN="CN=Client, OU=ec, O=ec, L=nanchang, S=jiangxi, C=CN"
3 set KS_PASS=-storepass strongit
4 set KEYINFO=-keyalg RSA
1 keytool -genkey -alias Server -dname %SERVER_DN% %KS_PASS% -keystore server.keystore %KEYINFO% -keypass strongit <br> keytool -export -alias Server -file test_axis.cer %KS_PASS% -keystore server.keystore <br> keytool -import -file test_axis.cer %KS_PASS% -keystore client.truststore -alias serverkey -noprompt <br><br> keytool -genkey -alias Client -dname %CLIENT_DN% %KS_PASS% -keystore client.keystore %KEYINFO% -keypass strongit <br> keytool -export -alias Client -file test_axis.cer %KS_PASS% -keystore client.keystore <br> keytool -import -file test_axis.cer %KS_PASS% -keystore server.truststore -alias clientkey -noprompt

好的,现在我们就有了四个文件:server.keystore,server.truststore,client.keystore,client.truststore

更改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即可。 private void Example() { String url =地址; Map param = new HashMap(); p.put("ParamName", "ParamValue"); String html = this.visitURL(url, param); }

㈢ 如何使用JAVA请求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

㈥ java怎么调用https外部接口

方法:只要New一个Map,然后把要传递的参数以键值对的形式存入Map即可。privatevoidExample(){Stringurl=地址;Mapparam=newHashMap();p.put("ParamName","ParamValue");Stringhtml=this.visitURL(url,param);}

㈦ 用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类型的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类型的webservice

public static org.apache.http.client.HttpClient wrapClient(org.apache.http.client.HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@SuppressWarnings("unused")
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
@SuppressWarnings("unused")
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {

}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {

}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry);
return new DefaultHttpClient(mgr, base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}

初始化httpclient 的时候加上:
HttpClient client = new DefaultHttpClient();
client = WebClientDevWrapper.wrapClient(client);
HttpPost post = new HttpPost(url);

㈩ 怎样用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相关的资料

热点内容
压缩因子定义 浏览:966
cd命令进不了c盘怎么办 浏览:212
药业公司招程序员吗 浏览:973
毛选pdf 浏览:659
linuxexecl函数 浏览:727
程序员异地恋结果 浏览:374
剖切的命令 浏览:228
干什么可以赚钱开我的世界服务器 浏览:290
php备案号 浏览:990
php视频水印 浏览:167
怎么追程序员的女生 浏览:487
空调外压缩机电容 浏览:79
怎么将安卓变成win 浏览:459
手机文件管理在哪儿新建文件夹 浏览:724
加密ts视频怎么合并 浏览:775
php如何写app接口 浏览:804
宇宙的琴弦pdf 浏览:396
js项目提成计算器程序员 浏览:944
pdf光子 浏览:834
自拍软件文件夹名称大全 浏览:328