java获取http:图片下载代码——android基础编

大家肯定很奇怪,为什么我写一编文章,原因是这样,android双向通信会用到协议,有http:协议, ftp: 协议,tip/ip  协议
所以我写一个JAVA小程序,让大家有所了解一下获取的流程。

package com.smart.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 org.junit.Test;



public class InternetTest {

	// 读取的方法

	public byte[] readStream(InputStream inStream) throws Exception {

		ByteArrayOutputStream outstream = new ByteArrayOutputStream();

		byte[] buffer = new byte[1024]; // 用数据装

		int len = -1;

		while ((len = inStream.read(buffer)) != -1) {

			outstream.write(buffer, 0, len);

		}

		outstream.close();

		inStream.close();

		// 关闭流一定要记得。

		return outstream.toByteArray();

	}



	@Test

	public void getImage() throws Exception {

		//要下载的图片的地址,

		String urlPath = "http://t2.gstatic.com/images?q=tbn:9g03SOE7gW2gEM:http://dev.10086.cn/cmdn/supesite";

		URL url = new URL(urlPath);//获取到路径

		// http协议连接对象

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		conn.setRequestMethod("GET");// 这里是不能乱写的,详看API方法

		conn.setConnectTimeout(6 * 1000);

		// 别超过10秒。

		System.out.println(conn.getResponseCode());

		if (conn.getResponseCode() == 200) {

			InputStream inputStream = conn.getInputStream();

			byte[] data = readStream(inputStream);

			File file = new File("smart.jpg");// 给图片起名子

			FileOutputStream outStream = new FileOutputStream(file);//写出对象

			outStream.write(data);// 写入

			outStream.close();	// 关闭流

		}

	}

}



你可能感兴趣的:(android)