Android心得8--Internet

1.从Internet获取数据

利用HttpURLConnection对象,我们可以从网络中获取网页数据.

URLurl = new URL("http://www.sohu.com");

HttpURLConnectionconn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5*1000);//设置连接超时

conn.setRequestMethod(“GET”);//以get方式发起请求

if(conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");

InputStreamis = conn.getInputStream();//得到网络返回的输入流

Stringresult = readData(is, "GBK");

conn.disconnect();

//第一个参数为输入流,第二个参数为字符集编码

publicstatic String readData(InputStream inSream, String charsetName) throwsException{

   ByteArrayOutputStream outStream = newByteArrayOutputStream();

   byte[] buffer = new byte[1024];

   int len = -1;

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

      outStream.write(buffer, 0, len);

   }

   byte[] data = outStream.toByteArray();

   outStream.close();

   inSream.close();

   return new String(data, charsetName);

}

利用HttpURLConnection对象,我们可以从网络中获取文件数据.

URLurl = new URL("http://photocdn.sohu.com/20100125/Img269812337.jpg");

HttpURLConnectionconn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5*1000);

conn.setRequestMethod("GET");

if(conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");

InputStreamis = conn.getInputStream();

readAsFile(is,"Img269812337.jpg");

 

publicstatic void readAsFile(InputStream inSream, File file) throws Exception{

   FileOutputStream outStream = new FileOutputStream(file);

   byte[] buffer = new byte[1024];

   int len = -1;

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

      outStream.write(buffer, 0, len);

   }

   outStream.close();

   inSream.close();

}

2. 多线程下载

使用多线程下载文件可以更快完成文件的下载,多线程下载文件之所以快,是因为其抢占的服务器资源多。如:假设服务器同时最多服务100个用户,在服务器中一条线程对应一个用户,100条线程在计算机中并非并发执行,而是由CPU划分时间片轮流执行,如果A应用使用了99条线程下载文件,那么相当于占用了99个用户的资源,假设一秒内CPU分配给每条线程的平均执行时间是10ms,A应用在服务器中一秒内就得到了990ms的执行时间,而其他应用在一秒内只有10ms的执行时间。就如同一个水龙头,每秒出水量相等的情况下,放990毫秒的水

肯定比放10毫秒的水要多。

多线程下载的实现过程:

1>首先得到下载文件的长度,然后设置本地文件的长度。

HttpURLConnection.getContentLength();

RandomAccessFilefile = new RandomAccessFile("QQWubiSetup.exe","rw");

file.setLength(filesize);//设置本地文件的长度

2>根据文件长度和线程数计算每条线程下载的数据长度和下载位置。如:文件的长度为6M,线程数为3,那么,每条线程下载的数据长度为2M,每条线程开始下载的位置如上图所示。

3>使用Http的Range头字段指定每条线程从文件的什么位置开始下载,如:指定从文件的2M位置开始下载文件,代码如下:

HttpURLConnection.setRequestProperty("Range","bytes=2097152-");

4>保存文件,使用RandomAccessFile类指定每条线程从本地文件的什么位置开始写入数据。

RandomAccessFilethreadfile = new RandomAccessFile("QQWubiSetup.exe ","rw");

threadfile.seek(2097152);//从文件的什么位置开始写入数据

3.向Internet发送请求参数

利用HttpURLConnection对象,我们可以向网络发送请求参数.

StringrequestUrl = "http://localhost:8080/itcast/contanctmanage.do";

Map<String,String> requestParams = new HashMap<String, String>();

requestParams.put("age","12");

requestParams.put("name","中国");

 StringBuilder params = new StringBuilder();

for(Map.Entry<String,String> entry : requestParams.entrySet()){

   params.append(entry.getKey());

   params.append("=");

   params.append(URLEncoder.encode(entry.getValue(),"UTF-8"));

   params.append("&");

}

if(params.length() > 0) params.deleteCharAt(params.length() - 1);

byte[]data = params.toString().getBytes();

URLrealUrl = new URL(requestUrl);

HttpURLConnectionconn = (HttpURLConnection) realUrl.openConnection();

conn.setDoOutput(true);//发送POST请求必须设置允许输出

conn.setUseCaches(false);//不使用Cache

conn.setRequestMethod("POST");        

conn.setRequestProperty("Connection","Keep-Alive");//维持长连接

conn.setRequestProperty("Charset","UTF-8");

conn.setRequestProperty("Content-Length",String.valueOf(data.length));

conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

DataOutputStreamoutStream = new DataOutputStream(conn.getOutputStream());

outStream.write(data);

outStream.flush();

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

        String result =readAsString(conn.getInputStream(), "UTF-8");

        outStream.close();

        System.out.println(result);

}

4.向Internet发送xml数据

利用HttpURLConnection对象,我们可以向网络发送xml数据.

StringBuilderxml =  new StringBuilder();

xml.append("<?xmlversion=\"1.0\" encoding=\"utf-8\" ?>");

xml.append("<M1V=10000>");

xml.append("<UI=1 D=\"N73\">中国</U>");

xml.append("</M1>");

byte[]xmlbyte = xml.toString().getBytes("UTF-8");

URLurl = newURL("http://localhost:8080/itcast/contanctmanage.do?method=readxml");

HttpURLConnectionconn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5*1000);

conn.setDoOutput(true);//允许输出

conn.setUseCaches(false);//不使用Cache

conn.setRequestMethod("POST");        

conn.setRequestProperty("Connection","Keep-Alive");//维持长连接

conn.setRequestProperty("Charset","UTF-8");

conn.setRequestProperty("Content-Length",String.valueOf(xmlbyte.length));

conn.setRequestProperty("Content-Type","text/xml; charset=UTF-8");

DataOutputStreamoutStream = new DataOutputStream(conn.getOutputStream());

outStream.write(xmlbyte);//发送xml数据

outStream.flush();

if(conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");

InputStreamis = conn.getInputStream();//获取返回数据

Stringresult = readAsString(is, "UTF-8");

outStream.close(); 

5.<!-- 访问internet权限 -->

<uses-permission

android:name="android.permission.INTERNET"/>

 

你可能感兴趣的:(多线程,android,String,buffer,byte,internet)