import static org.junit.Assert.fail;
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 org.junit.Test;
public class InternetTest {
@Test
public void test() {
fail("Not yet implemented");
}
@Test
public void getImage() throws Exception{
//首先要獲取請求的路徑,路徑就是要從網上獲取的資源
String urlPath= "http://c.hiphotos.baidu.com/image/pic/item/8718367adab44aedbc2df1e3b01c8701a18bfb52.jpg";
URL url = new URL(urlPath);//建立URL類對象,拋出異常
HttpURLConnection conn =(HttpURLConnection)url.openConnection();//得到UrlConnection對象
conn.setRequestMethod("GET");//聲明請求方式
conn.setConnectTimeout(6*1000);//設置連接超時
if(conn.getResponseCode() == 200){//如果結果是200,就代表他的請求是成功的
InputStream inputStream = conn.getInputStream();//得到服務器端傳回來的數據,相對客戶端爲輸入流
byte[] data = readInstream(inputStream);
File file = new File("touxiang.jpg");
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(data);
outputStream.close();
}
}
private byte[] readInstream(InputStream inputStream) throws Exception{
ByteArrayOutputStream byteArrayOutPutStream = new ByteArrayOutputStream();//創建ByteArrayOutputStream類
byte[] buffer = new byte[1024];//聲明緩存區
int length = -1;//定義讀取的默認長度
while((length = inputStream.read(buffer))!= -1){
byteArrayOutPutStream.write(buffer,0,length);//把緩存區中的輸入到內存中
};
byteArrayOutPutStream.close();//關閉輸入流
inputStream.close();//關閉輸入流
return byteArrayOutPutStream.toByteArray();//返回這個輸入流的字節數組
}
}
J2SE從網絡中獲取文本
@Test
public void getHtml() throws Exception{
String urlpathString = "http://www.sina.com";
URL url = new URL(urlpathString);//建立URL對象,拋出異常
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(6*1000);
if(conn.getResponseCode() == 200){
InputStream inputStream = conn.getInputStream();//得到輸入流
byte[] data = readInstream(inputStream); //得到數據
System.out.println(new String(data));//將字節轉化爲字符串,打印在控制檯上面
}
}
System.out.println(new String(data)); 是將得到的字符串類型打印到控制檯上面,返回是HTML的代碼,和流量器參看的源代碼是一樣的。
第三種:J2SE從網絡獲取可以自行的文件。
在Internet類中添加getFile()方法,具體代碼如下:
@Test
public void getFile() throws Exception{
String urlPath = "http://dlsw.baidu.com/sw-search-sp/soft/b8/14630/YoudaoDict_V6.3.66.1117_setup.1423550350.exe";
URL url = new URL(urlPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(6*1000);
if(connection.getResponseCode()== 200){
InputStream inputStream =connection.getInputStream();
byte[] data =readInstream(inputStream);
File file =new File("youdao.exe");
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(data);
outputStream.close();
}
}