Chinaunix首页 | 论坛 | 博客
  • 博客访问: 892602
  • 博文数量: 322
  • 博客积分: 6688
  • 博客等级: 准将
  • 技术积分: 3626
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-19 11:26
文章分类

全部博文(322)

文章存档

2013年(5)

2012年(66)

2011年(87)

2010年(164)

分类: Java

2011-01-07 09:29:29

Java工程

InternetTest

Java代码

  1. package junit.test;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.File;
  5. import java.io.FileOutputStream;
  6. import java.io.InputStream;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. import org.junit.Test;
  10. import junit.framework.TestCase;
  11.  
  12. public class InternetTest extends TestCase {
  13.  
  14.     public byte[] readStream(InputStream inputStream) throws Exception {
  15.         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  16.         byte[] buffer = new byte[1024];
  17.         int len = -1;
  18.         while ((len = inputStream.read(buffer)) != -1) {
  19.             outputStream.write(buffer, 0, len);
  20.         }
  21.         outputStream.close();
  22.         inputStream.close();
  23.         return outputStream.toByteArray();
  24.     }
  25.  
  26.     // 请求图片
  27.     @Test
  28.     public void testGetImage() throws Exception {
  29.         String urlpath = "";
  30.         URL url = new URL(urlpath);
  31.         // 利用HttpURLConnection对象,我们可以从网络中获取网页数据
  32.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  33.         // 如果超过android的组件阻塞时间,就会被系统回收
  34.         // 设置连接超时
  35.         conn.setConnectTimeout(6 * 1000);
  36.         conn.setRequestMethod("GET");
  37.         if (conn.getResponseCode() == 200) {
  38.             // 得到网络返回的输入流
  39.             InputStream inputStream = conn.getInputStream();
  40.             byte[] data = readStream(inputStream);
  41.             File file = new File("baidu.jpg");
  42.             FileOutputStream outputStream = new FileOutputStream(file);
  43.             outputStream.write(data);
  44.             outputStream.close();
  45.         } else {
  46.             throw new RuntimeException("请求url失败");
  47.         }
  48.     }
  49.  
  50.     // 请求
  51.     @Test
  52.     public void testGetHtml() throws Exception {
  53.         String urlpath = "";
  54.         URL url = new URL(urlpath);
  55.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  56.         conn.setConnectTimeout(6 * 1000);
  57.         conn.setRequestMethod("GET");
  58.         if (conn.getResponseCode() == 200) {
  59.             InputStream inputStream = conn.getInputStream();
  60.             byte[] data = readStream(inputStream);
  61.             System.out.println(new String(data));
  62.         } else {
  63.             throw new RuntimeException("请求url失败");
  64.         }
  65.     }
  66. }



阅读(862) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~