Java Http編程中常見的實現方式是使用Java 提供的API,另外就是使用Apache提供的 API1、通過Java提供的API實現Http編程 類:URL:類 URL 代表一個統一資源定位符,它是指向互聯網“資源”的指針。 HttpURLConnection:支持 HTTP 特定功能的 URLConnection URLConnection 抽象類是所有類的超類,它代表應用程序和 URL 之間的通信鏈接。此類的實例可用于讀取和寫入此 URL 引用的資源 1.1、下載數據(以下載一直圖片為例) import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;public class DownloadImage { public static void main(String[] args) throws IOException { //資源的URL:就是一個資源的連接,URL中的參數淡然也可以是網上的一些圖片或者其他資源的連接了 //例如把http://localhost:8080/Day_0818/aa.jpg換為http://home.VEVb.com/images/logo_home.gif下載博客園的logo,當然存儲 到時候要改后綴了 URL url = new URL("http://localhost:8080/Day_0818/aa.jpg"); //通過url獲取一個封裝了http協議的URL連接對象:HttpURLConnection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //設置連接的請求方式,因為是獲取數據,所以請求方式為GET:必須大寫 connection.setRequestMethod("GET"); //設置是否能夠獲取連接的輸入流,默認就是true,也可以不寫這條語句 connection.setDoInput(true); //有了連接,就要打開連接 connection.connect(); //獲取響應碼 int code = connection.getResponseCode(); //響應碼是200則表示連接成功響應 if(200 == code){ //獲取連接 的輸入流 InputStream is = connection.getInputStream(); //文件輸出流對象,(創建存放資源的文件) FileOutputStream fos = new FileOutputStream("e://aa.jpg"); //字節數組,我理解為輸入流和輸出流的一個中介,輸入流把數據放到數組里讓輸出流讀取 byte[] b = new byte[1024]; int length = -1; while((length = is.read(b)) != -1){ fos.write(b, 0, length); fos.flush(); } //關閉流 fos.close(); } }}----------------------------------------------------------------------------------------//post方式來模擬登錄。/*需要創建LoginServlet類接收數據*/import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;//http://localhost:8080/MyServer/loginServlet?username=admin&userpwd=111public class URLDemo2 { public static void main(String[] args) throws Exception { String path = "http://localhost:8080/MyServer/loginServlet"; URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(30000); connection.setDoInput(true); connection.setDoOutput(true); //username=admin&userpwd=111 /* * 將用戶名和密碼改成用戶輸入的數據。 */ OutputStream os = connection.getOutputStream(); os.write("username=admin&userpwd=111".getBytes()); connection.connect(); int code = connection.getResponseCode(); if(code==200){ InputStream is = connection.getInputStream(); byte[] b = new byte[1024]; int length = is.read(b); System.out.PRintln(new String(b,0,length)); is.close(); } }} 新聞熱點
疑難解答