當前位置:首頁 » 編程語言 » java調用https

java調用https

發布時間: 2023-02-13 19:17:03

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之後再運行。

熱點內容
java刪除數組元素 發布:2024-11-08 20:39:48 瀏覽:947
網狐6603編譯 發布:2024-11-08 20:38:20 瀏覽:472
編程老頑童 發布:2024-11-08 20:37:43 瀏覽:58
手機上能搭建ftp伺服器嗎 發布:2024-11-08 20:33:30 瀏覽:205
linux抓包工具 發布:2024-11-08 20:25:07 瀏覽:459
我的世界神奇寶貝伺服器聯機生存 發布:2024-11-08 20:17:07 瀏覽:723
溫州少兒編程 發布:2024-11-08 20:16:28 瀏覽:550
伺服器硬體有什麼 發布:2024-11-08 20:13:52 瀏覽:320
windows存儲分層 發布:2024-11-08 20:04:34 瀏覽:754
淘寶客服電腦伺服器 發布:2024-11-08 19:39:26 瀏覽:911