㈠ 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
//處理http請求requestUrl為請求地址requestMethod請求方式,值為"GET"或"POST"
publicstaticStringhttpRequest(StringrequestUrl,StringrequestMethod,StringoutputStr){
StringBufferbuffer=null;
try{
URLurl=newURL(requestUrl);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod(requestMethod);
conn.connect();
//往伺服器端寫內容也就是發起http請求需要帶的參數
if(null!=outputStr){
OutputStreamos=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//讀取伺服器端返回的內容
InputStreamis=conn.getInputStream();
InputStreamReaderisr=newInputStreamReader(is,"utf-8");
BufferedReaderbr=newBufferedReader(isr);
buffer=newStringBuffer();
Stringline=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
}catch(Exceptione){
e.printStackTrace();
}
returnbuffer.toString();
}
㈣ 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
//處理http請求requestUrl為請求地址requestMethod請求方式,值為"GET"或"POST"
publicstaticStringhttpRequest(StringrequestUrl,StringrequestMethod,StringoutputStr){
StringBufferbuffer=null;
try{
URLurl=newURL(requestUrl);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod(requestMethod);
conn.connect();
//往伺服器端寫內容也就是發起http請求需要帶的參數
if(null!=outputStr){
OutputStreamos=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//讀取伺服器端返回的內容
InputStreamis=conn.getInputStream();
InputStreamReaderisr=newInputStreamReader(is,"utf-8");
BufferedReaderbr=newBufferedReader(isr);
buffer=newStringBuffer();
Stringline=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
}catch(Exceptione){
e.printStackTrace();
}
returnbuffer.toString();
}
㈥ 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;
}