Android学习笔记(十五) Http

1、Http协议概要

  • 应用程序和服务间的请求/响应是无状态的,即响应完即断开连接。
  • HttpClient库是Android自带的,故无需引入该库

2、Http请求和获取数据

  1. 生成代表客户端的HttpClient对象
  2. 生成代表请求的HttpGet对象
  3. 发送请求,获得服务器端的HttpResponse对象
  4. 检查响应状态是否正常
  5. 获取响应对象当中的数据

原则:在主线程当中不能访问网络!

class NeworkThread extents Thread{
    @Override
    public void run(){
        //创建HttpClient
        HttpClient httpClient = new DefaultHttpClient();
        //创建代表请求的对象,参数是访问的服务器地址
        HttpGet httpGet = new HttpGet("http://www.marschen.com/data1.html");
        
        //执行请求,获取服务器发还的响应对象
        HttpResponse resp = HttpClient.execute(httpGet);
        
        //检查响应状态是否正常,如果等于200则正常
        int code = resp.getStatusLine().getStatusCode();
        
        if(code == 200){
            //从响应对象中取出数据
            HttpEntity entity = resp.getEntity();
            InputStream in = entity.gitContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line = reader.readLine();
            log.d("HTTP","从服务器取得的数据为"+line);
        }
    }
}

3、使用Http协议下载文件

这里要分两种情况讨论,因为下载文档可以用更简单的方法实现,而且很多文档是需要按行读取的。

3.1 下载文档

  1. 创建一个URL对象
  2. 通过URL对象,创建一个HttpURLConnection对象
  3. 得到InputStream
  4. 从InputStream当中读数据
        public String download(String urlStr){
            StringBuffer sb = new StringBuffer();
            //A string buffer is like a String,but can be modified. 
            //but the length and content of the sequence can be changed through certain method calls(append,reverse,insert,charAt....).
            
            String line = null;
            BufferedReader bf = null;
            
            try {
                //创建一个URL对象
                url = new URL(urlStr);
                
                //创建一个Http连接
                HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
                
                //使用BufferedReader来读数据
                bf = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                while ((line = bf.readLine()) != null){
                    sb.append(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }

3.2 下载文件

为了实现起来更简单,而且考虑到以后会经常用,所以先把关于文件与SD卡相关的一些操作封装到一个FileUtils类里。

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;

public class FileUtils {
    private String SDPATH;
    
    public FileUtils(){
        //得到当前外部存储设备的目录
        SDPATH = Environment.getExternalStorageDirectory()+"/";
    }
    
    /*
     * 在SD卡上创建文件
     */
    public File createSDFile(String fileName) throws IOException{
        File file = new File(SDPATH + fileName);
        file.createNewFile();
        return file;
    }
    
    /*
     * 在SD卡上创建目录
     */
    public File createSDDir(String dirName){
        File dir = new File(SDPATH + dirName);
        dir.mkdir();
        return dir;
    }
    
    /*
     * 判断文件是否存在
     */
    boolean isFileExist(String fileName){
        File file = new File(fileName);
        return file.exists();
    }
    
    /*
     * 将InputStream中的文件写入到SD卡中
     */
    public File writeIntoSDFromInput(String path,String fileName,InputStream inputStream){
        File file = null;
        OutputStream os = null;
        
        try {
            file = createSDFile(path + fileName);
            os = new FileOutputStream(file);
            byte [] buffer = new byte[1024*4];
            while((inputStream.read(buffer)) != -1){
                os.write(buffer);
            }
            os.flush();//刷新缓冲,将缓冲区中的数据全部取出来
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                inputStream.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }
        return file;
    }
}

然后是具体实现方法。其实有将url转化成为InputStream的方法和下载文档是相同的,所以同样是为了以后使用方便,将其写成一个方法。区别是在得到InputStream对象后的不同处理方法。

/*
     * 返回-1:代表下载文件出错;返回0,:代表下载文件成功;返回1:代表文件已经存在
     */
    public int downloadFile(String urlStr,String path,String fileName){
        InputStream inputStream = null;
        FileUtils fileUtils = new FileUtils();
        
        if(fileUtils.isFileExist(path + fileName)){
            return 1;
        }
        else{
            inputStream = urlStrToInputStream(urlStr);
            File resultFile = fileUtils.writeIntoSDFromInput(path, fileName, inputStream);
            if(resultFile == null){
                return -1;
            }
        }
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
    
    //将字符串类型的url转化成为InputStream。读取数据通过InputStream实现。
    public InputStream urlStrToInputStream(String urlStr){
        URL url = null;
        InputStream inputStream = null;
        try {
            url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); 
            inputStream = urlConnection.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }
原文地址:https://www.cnblogs.com/viaduct/p/6422228.html