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

java調用https介面

發布時間: 2023-08-13 17:49:39

⑴ 怎樣用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客戶端

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

當出現了:Enter certificate to add to trusted keystore or 'q' to quit: [1]
這行代碼時,輸入1,回車。正常執行完後在D盤根目錄下就會出現證書「jssecacerts」文件,

得到證書後將證書拷貝到$JAVA_HOME/jre/lib/security目錄下,我這里是win7系統,在嘗試的過程中需要將證書重命名為:cacerts 放進去才會有用。(這個步驟在不同的環境和操作系統下有點不同,需要注意)

⑷ 使用https訪問http/https通信協議,需要哪些配置文件

項目里需要訪問其他介面,通過http/https協議。我們一般是用HttpClient類來實現具體的http/https協議介面的調用。

// Init a HttpClient
HttpClient client = new HttpClient();
String url=http://www.xxx.com/xxx;

// Init a HttpMethod
HttpMethod get = new GetMethod(url);
get.setDoAuthentication(true);
get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false));

// Call http interface
try {
client.executeMethod(get);

// Handle the response from http interface
InputStream in = get.getResponseBodyAsStream();
SAXReader reader = new SAXReader();
Document doc = reader.read(in);
} finally {
// Release the http connection
get.releaseConnection();
}

以上代碼在通過普通的http協議是沒有問題的,但如果是https協議的話,就會有證書文件的要求了。一般情況下,是這樣去做的。

// Init a HttpClient
HttpClient client = new HttpClient();
String url=https://www.xxx.com/xxx;

if (url.startsWith("https:")) {
System.setProperty("javax.net.ssl.trustStore", "/.sis.cer");
System.setProperty("javax.net.ssl.trustStorePassword", "public");
}

於是,這里就需要事先生成一個.sis.cer的文件,生成這個文件的方法一般是先通過瀏覽器訪問https://,導出證書文件,再用JAVA keytool command 生成證書

# $JAVA_HOME/bin/keytool -import -file sis.cer -keystore .sis.cer

但這樣做,一比較麻煩,二來證書也有有效期,過了有效期之後,又需要重新生成一次證書。如果能夠避開生成證書文件的方式來使用https的話,就比較好了。

還好,在最近的項目里,我們終於找到了方法。

// Init a HttpClient
HttpClient client = new HttpClient();
String url=https://www.xxx.com/xxx;

if (url.startsWith("https:")) {
this.supportSSL(url, client);
}

用到了supportSSL(url, client)這個方法,看看這個方法是如何實現的。

private void supportSSL(String url, HttpClient client) {
if(StringUtils.isBlank(url)) {
return;
}
String siteUrl = StringUtils.lowerCase(url);
if (!(siteUrl.startsWith("https"))) {
return;
}

try {
setSSLProtocol(siteUrl, client);
} catch (Exception e) {
logger.error("setProtocol error ", e);
}
Security.setProperty( "ssl.SocketFactory.provider",
"com.tool.util.DummySSLSocketFactory");
}

private static void setSSLProtocol(String strUrl, HttpClient client) throws Exception {

URL url = new URL(strUrl);
String host = url.getHost();
int port = url.getPort();

if (port <= 0) {
port = 443;
}
ProtocolSocketFactory factory = new SSLSocketFactory();
Protocol authhttps = new Protocol("https", factory, port);
Protocol.registerProtocol("https", authhttps);
// set https protocol
client.getHostConfiguration().setHost(host, port, authhttps);
}

在supportSSL方法里,調用了Security.setProperty( "ssl.SocketFactory.provider",
"com.tool.util.DummySSLSocketFactory");
那麼這個com.tool.util.DummySSLSocketFactory是這樣的:
訪問https 資源時,讓httpclient接受所有ssl證書,在weblogic等容器中很有用
代碼如下:
1. import java.io.IOException;
2. import java.net.InetAddress;
3. import java.net.InetSocketAddress;
4. import java.net.Socket;
5. import java.net.SocketAddress;
6. import java.net.UnknownHostException;
7. import java.security.KeyManagementException;
8. import java.security.NoSuchAlgorithmException;
9. import java.security.cert.CertificateException;
10. import java.security.cert.X509Certificate;
11.
12. import javax.net.SocketFactory;
13. import javax.net.ssl.SSLContext;
14. import javax.net.ssl.TrustManager;
15. import javax.net.ssl.X509TrustManager;
16.
17. import org.apache.commons.httpclient.ConnectTimeoutException;
18. import org.apache.commons.httpclient.params.HttpConnectionParams;
19. import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
20.
21. public class MySecureProtocolSocketFactory implements SecureProtocolSocketFactory {
22. static{
23. System.out.println(">>>>in MySecureProtocolSocketFactory>>");
24. }
25. private SSLContext sslcontext = null;
26.
27. private SSLContext createSSLContext() {
28. SSLContext sslcontext=null;
29. try {
30. sslcontext = SSLContext.getInstance("SSL");
31. sslcontext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
32. } catch (NoSuchAlgorithmException e) {
33. e.printStackTrace();
34. } catch (KeyManagementException e) {
35. e.printStackTrace();
36. }
37. return sslcontext;
38. }
39.
40. private SSLContext getSSLContext() {
41. if (this.sslcontext == null) {
42. this.sslcontext = createSSLContext();
43. }
44. return this.sslcontext;
45. }
46.
47. public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
48. throws IOException, UnknownHostException {
49. return getSSLContext().getSocketFactory().createSocket(
50. socket,
51. host,
52. port,
53. autoClose
54. );
55. }
56.
57. public Socket createSocket(String host, int port) throws IOException,
58. UnknownHostException {
59. return getSSLContext().getSocketFactory().createSocket(
60. host,
61. port
62. );
63. }
64.
65.
66. public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
67. throws IOException, UnknownHostException {
68. return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
69. }
70.
71. public Socket createSocket(String host, int port, InetAddress localAddress,
72. int localPort, HttpConnectionParams params) throws IOException,
73. UnknownHostException, ConnectTimeoutException {
74. if (params == null) {
75. throw new IllegalArgumentException("Parameters may not be null");
76. }
77. int timeout = params.getConnectionTimeout();
78. SocketFactory socketfactory = getSSLContext().getSocketFactory();
79. if (timeout == 0) {
80. return socketfactory.createSocket(host, port, localAddress, localPort);
81. } else {
82. Socket socket = socketfactory.createSocket();
83. SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
84. SocketAddress remoteaddr = new InetSocketAddress(host, port);
85. socket.bind(localaddr);
86. socket.connect(remoteaddr, timeout);
87. return socket;
88. }
89. }
90.
91. //自定義私有類
92. private static class TrustAnyTrustManager implements X509TrustManager {
93.
94. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
95. }
96.
97. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
98. }
99.
100. public X509Certificate[] getAcceptedIssuers() {
101. return new X509Certificate[]{};
102. }
103. }
104.
105. }

public class MySecureProtocolSocketFactory implements SecureProtocolSocketFactory {
static{
System.out.println(">>>>in MySecureProtocolSocketFactory>>");
}
private SSLContext sslcontext = null;

private SSLContext createSSLContext() {
SSLContext sslcontext=null;
try {
sslcontext = SSLContext.getInstance("SSL");
sslcontext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return sslcontext;
}

private SSLContext getSSLContext() {
if (this.sslcontext == null) {
this.sslcontext = createSSLContext();
}
return this.sslcontext;
}

public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(
socket,
host,
port,
autoClose
);
}

public Socket createSocket(String host, int port) throws IOException,
UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(
host,
port

然後按如下方式使用HttpClient
Protocol myhttps = new Protocol("https", new MySecureProtocolSocketFactory (), 443);
Protocol.registerProtocol("https", myhttps);
HttpClient httpclient=new HttpClient();

⑸ java怎麼調用https外部介面

方法:只要New一個Map,然後把要傳遞的參數以鍵值對的形式存入Map即可。privatevoidExample(){Stringurl=地址;Mapparam=newHashMap();p.put("ParamName","ParamValue");Stringhtml=this.visitURL(url,param);}

熱點內容
c語言取隨機數 發布:2025-02-06 02:46:57 瀏覽:863
uc緩存的視頻卡住 發布:2025-02-06 02:17:05 瀏覽:144
解壓同學介紹 發布:2025-02-06 02:13:10 瀏覽:776
icsftp 發布:2025-02-06 02:12:59 瀏覽:325
ftp跨域上傳文件 發布:2025-02-06 02:09:22 瀏覽:822
非遞歸全排列演算法 發布:2025-02-06 02:06:45 瀏覽:551
vs反編譯dll 發布:2025-02-06 02:06:00 瀏覽:584
ubuntu設置ftp許可權 發布:2025-02-06 01:54:07 瀏覽:599
奇瑞5哪個配置值得買 發布:2025-02-06 01:51:56 瀏覽:552
黑鯊手機哪裡看安卓版本 發布:2025-02-06 01:36:04 瀏覽:803