Java作為一種面向?qū)ο缶幊陶Z(yǔ)言,具有訪問(wèn)Http和Https協(xié)議的能力。在進(jìn)行Java編程時(shí),如果需要與網(wǎng)絡(luò)進(jìn)行交互,就需要使用Http和Https協(xié)議進(jìn)行通信。下面通過(guò)示例代碼介紹如何在Java中訪問(wèn)Http和Https協(xié)議。
Http協(xié)議是基于TCP/IP協(xié)議棧的應(yīng)用層協(xié)議,Java提供了兩種常用的Http客戶端工具:URLConnection和HttpClient。
//示例使用URLConnection實(shí)現(xiàn)Http GET請(qǐng)求 URL url = new URL("http://www.example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); conn.disconnect();
Https協(xié)議是在Http協(xié)議基礎(chǔ)上增加了一層SSL/TLS安全協(xié)議,Java提供了JSSE(Java Secure Socket Extension)包用于實(shí)現(xiàn)和處理SSL/TLS通信。
//示例使用JSSE實(shí)現(xiàn)Https GET請(qǐng)求 SSLContext sslcontext = SSLContext.getInstance("TLS"); TrustManager[] tm = {new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {} public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return null; } }}; sslcontext.init(null, tm, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); URL url = new URL("https://www.example.com"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(ssf); conn.setRequestMethod("GET"); conn.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); conn.disconnect();
以上代碼僅供參考,實(shí)際使用時(shí)還需要根據(jù)具體情況進(jìn)行配置和優(yōu)化。