android學習筆記14————–Internet(1)

上一篇:/kf/201202/120057.html

[java]
建立java工程的單元測試。 

 註意單元測試方法的函數名,要以test開始,否則會報錯。

import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
 
import junit.framework.TestCase; 
 
import org.junit.Test; 
 
 
public class TestInternet extends TestCase 

    public byte[] readStream(InputStream inputStream) throws Exception 
    { 
        byte[] buffer=new byte[1024]; 
        int len=-1; 
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); 
         
        while((len=inputStream.read(buffer))!=-1) 
        { 
            byteArrayOutputStream.write(buffer,0,len); 
        } 
         
        inputStream.close(); 
        byteArrayOutputStream.close(); 
        return byteArrayOutputStream.toByteArray(); 
    } 
     
    @Test public void testGetImage() throws Exception 
    { 
        String urlpath="/wp-content/images1/20181007/search-logo459.png";//網上圖片的地址 
        URL url=new URL(urlpath); 
        HttpURLConnection conn=(HttpURLConnection)url.openConnection(); 
        conn.setConnectTimeout(6*1000);  //設置鏈接超時時間6s  
            //在android系統中,如果超過組件的阻塞時間,組件會被系統回收。時間大約10s。  
        conn.setRequestMethod("GET"); 
        System.out.println(conn.getResponseCode()); 
        if(conn.getResponseCode()==200) 
        { 
            InputStream inputStream=conn.getInputStream(); 
            byte[] data=readStream(inputStream); 
            File file=new File("logo.png"); 
            FileOutputStream fileOutputStream=new FileOutputStream(file); 
            fileOutputStream.write(data); 
            fileOutputStream.close(); 
        } 
    } 

 按f5刷新後,

 

 

打開後,即為網頁圖片

 

摘自 奔跑的蝸牛
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *