隻知道浏覽器使用的是http協定,那麼如何将網絡資源使用javahttp下載下傳下來呢!
這隻是一個非常簡單的小示例,隻是不想每次碰到關于此方面的内容忘了就無從下手!
示例建立httpurlconnection網絡連接配接,并将這個連接配接獲得的網絡資料流寫道本地磁盤!
示例代碼如下:
package imageview;
import java.io.bytearrayoutputstream;
import java.io.file;
import java.io.fileoutputstream;
import java.io.inputstream;
import java.net.httpurlconnection;
import java.net.url;
/**
* @說明 從網絡擷取圖檔到本地
* @author 崔素強
* @version 1.0
* @since
*/
public class getimage {
/**
* 測試
* @param args
*/
public static void main(string[] args) {
string url = "http://www.baidu.com/img/baidu_sylogo1.gif";
byte[] btimg = getimagefromnetbyurl(url);
if(null != btimg && btimg.length > 0){
system.out.println("讀取到:" + btimg.length + " 位元組");
string filename = "百度.gif";
writeimagetodisk(btimg, filename);
}else{
system.out.println("沒有從該連接配接獲得内容");
}
}
* 将圖檔寫入到磁盤
* @param img 圖檔資料流
* @param filename 檔案儲存時的名稱
public static void writeimagetodisk(byte[] img, string filename){
try {
file file = new file("c:\\" + filename);
fileoutputstream fops = new fileoutputstream(file);
fops.write(img);
fops.flush();
fops.close();
system.out.println("圖檔已經寫入到c盤");
} catch (exception e) {
e.printstacktrace();
* 根據位址獲得資料的位元組流
* @param strurl 網絡連接配接位址
* @return
public static byte[] getimagefromnetbyurl(string strurl){
url url = new url(strurl);
httpurlconnection conn = (httpurlconnection)url.openconnection();
conn.setrequestmethod("get");
conn.setconnecttimeout(5 * 1000);
inputstream instream = conn.getinputstream();//通過輸入流擷取圖檔資料
byte[] btimg = readinputstream(instream);//得到圖檔的二進制資料
return btimg;
return null;
* 從輸入流中擷取資料
* @param instream 輸入流
* @throws exception
public static byte[] readinputstream(inputstream instream) throws exception{
bytearrayoutputstream outstream = new bytearrayoutputstream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=instream.read(buffer)) != -1 ){
outstream.write(buffer, 0, len);
instream.close();
return outstream.tobytearray();
}