大家肯定很奇怪,为什么我写一编文章,原因是这样,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);
-
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("GET");
- conn.setConnectTimeout(6 * 1000);
-
- 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();
- }
- }
- }
本文转自 llb988 51CTO博客,原文链接:http://blog.51cto.com/llb988/491055,如需转载请自行联系原作者