美文网首页网络
029_Android Http的基本使用方法

029_Android Http的基本使用方法

作者: wakawakai | 来源:发表于2019-08-02 17:00 被阅读7次

    http协议 :超文本传输协议

    请求协议 request 响应协议 response
    请求首行 响应首行
    请求头信息 响应头信息
    空行 空行
    请求体 响应体

    Fiddler

    Fiddler是一个http协议调试代理工具,它能够记录并检查所有你的电脑和互联网之间的http通讯,设置断点,查看所有的“进出”Fiddler的数据(指cookie,html,js,css等文件)。

    GET请求抓包演示

    GET.png

    GET请求和POST请求的区别

    get请求直接将请求参数暴露在url,不安全+一般用于向服务器请求数据,get请求没有请求体
    post请求将请求参数放在请求体里面,安全的+一般用于向服务器提交数据

    网络七层协议图.jpg
    1. 应用层 :应用程序,用户看得见的http协议

    2. 表示层:将人看的懂的转成计算机看的懂

    3. 会话层:发起一个连接

    4. 传输层:规定传输协议和端口号 TCP协议,UDP协议

    5. 网络层:规定网络ip ip协议

    6. 数据链路层

    7. 物理层:光缆、网线

    文件下载(GET请求)

    import androidx.appcompat.app.AppCompatActivity;
    
    import android.annotation.SuppressLint;
    import android.media.MediaPlayer;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.SurfaceHolder;
    import android.view.SurfaceView;
    import android.view.View;
    import android.widget.SeekBar;
    import android.widget.Toast;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InterruptedIOException;
    import java.io.RandomAccessFile;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    
    public class PracticeActivity extends AppCompatActivity {
    
        private String TAG = "##";
        private SeekBar seekBar;
        private SurfaceView surfaceView;
        private AsyncTask<String, Integer, String> downloadAsyncTask, continueAsyncTask;
        //存储文件的路径
        private String filePath = "/sdcard/Video.mp4";
        //要下载文件的url
        private String url = "http://vodkgeyttp8.vod.126.net/cloudmusic/NjEyMTk1NjU=/dcec07fa4375312402fbd8e8ecb851e8/37dd00b0a2a6c4e788eeecdfef33d73d.mp4?wsSecret=6c21bd623bd80249c965220eba59f7f8&wsTime=1564728030";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_practice);
            seekBar = findViewById(R.id.seekBar);
        }
    
        //三个按钮的监听
        public void click(View view) {
            switch (view.getId()) {
                case R.id.downloadButton:
                    download();
                    break;
                case R.id.pauseButton:
                    //关闭异步任务
                    if (downloadAsyncTask != null) {
                        downloadAsyncTask.cancel(true);
                    }
                    if (continueAsyncTask != null) {
                        continueAsyncTask.cancel(true);
                    }
                    break;
                case R.id.continueButton:
                    continueDowbload();
                    break;
            }
        }
    
    
        @SuppressLint("StaticFieldLeak")
        private void continueDowbload() {
            continueAsyncTask = new AsyncTask<String, Integer, String>() {
                @SuppressLint("WrongThread")
                @Override
                protected String doInBackground(String... strings) {
                    File file = new File(filePath);
                    //上一次下载的大小
                    int start = 0;
                    //总大小
                    int end = 0;
                    try {
                        HttpURLConnection connection = (HttpURLConnection) new URL(strings[0]).openConnection();
                        connection.connect();
                        if (connection.getResponseCode() == 200) {
                            start = (int) file.length();
                            end = connection.getContentLength();
                            Log.i(TAG, "doInBackground: 请求成功");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (start == end) {
                        Log.i(TAG, "doInBackground: GG");
                        return "下载完成";
                    }
    
                    InputStream is = null;
                    RandomAccessFile raf = null;
    
                    try {
                        HttpURLConnection connection = (HttpURLConnection) new URL(strings[0]).openConnection();
                        //设置请求体
                        connection.setRequestProperty("Range", "bytes=" + start + "-" + end);
                        connection.connect();
                        if (connection.getResponseCode() == 206) {
                            Log.i(TAG, "doInBackground: 开始第二次");
                            seekBar.setMax(end);
                            publishProgress(start);
                            is = connection.getInputStream();
                            //随机访问流
                            raf = new RandomAccessFile(filePath, "rw");
                            //设置写入位置
                            raf.seek(start);
                            int length = 0;
                            byte[] bytes = new byte[1024 * 8];
                            Log.i(TAG, "doInBackground: 再次写入");
                            while ((length = is.read(bytes)) != -1) {
                                raf.write(bytes, 0, length);
                                start += length;
                                publishProgress(start);
                            }
                            return "下载完成";
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (raf != null) {
                            try {
                                raf.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    return "下载失败";
                }
    
                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    Toast.makeText(PracticeActivity.this, s, Toast.LENGTH_SHORT).show();
                }
    
                @Override
                protected void onProgressUpdate(Integer... values) {
                    super.onProgressUpdate(values);
                    seekBar.setProgress(values[0]);
                }
            }.execute(url);
        }
    
        @SuppressLint("StaticFieldLeak")
        private void download() {
            //异步任务
            downloadAsyncTask = new AsyncTask<String, Integer, String>() {
                @SuppressLint("WrongThread")
                @Override
                protected String doInBackground(String... strings) {
                    InputStream is = null;
                    FileOutputStream os = null;
                    try {
                        //请求连接
                        URL url = new URL(strings[0]);
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.connect();
    
                        //判断请求码
                        if (connection.getResponseCode() == 200) {
                            //获得请求数据的大小
                            int contentLength = connection.getContentLength();
                            //设置最大进度
                            seekBar.setMax(contentLength);
                            //获得输入 输出流
                            is = connection.getInputStream();
                            os = new FileOutputStream(filePath);
                            //每次读取的长度
                            int length = 0;
                            //当前下载的进度
                            int currentProgress = 0;
                            byte[] bytes = new byte[1024 * 8];
                            //开始下载
                            while ((length = is.read(bytes)) != -1) {
                                os.write(bytes, 0, length);
                                currentProgress += length;
                                //发布进度
                                publishProgress(currentProgress);
                            }
                        }
                        return "下载完成";
    
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
    
    
                        //关闭资源
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (os != null) {
                            try {
                                os.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    return "下载失败";
                }
    
                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    Toast.makeText(PracticeActivity.this, s, Toast.LENGTH_SHORT).show();
                }
    
                @Override
                protected void onProgressUpdate(Integer... values) {
                    super.onProgressUpdate(values);
                    //更新进度
                    seekBar.setProgress(values[0]);
                }
            }.execute(url);
        }
    
    }
    

    文件上传(POST请求)

    
        private String upload(String uploadFileUrl, File uploadFile) {
            OutputStream os = null;
            FileInputStream is = null;
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(uploadFileUrl).openConnection();
                //设置连接方式
                connection.setRequestMethod("POST");
                //设置可输出
                connection.setDoOutput(true);
                //拼接请求体
                StringBuffer requestBody = new StringBuffer();
                requestBody.append("-----------------------------7e324741816d4\r\n");
                requestBody.append("Content-Disposition: form-data; name=\"file\"; filename=" + uploadFile.getName() + "\r\n");
                requestBody.append("Content-Type: image/*" + "\r\n");
                requestBody.append("\r\n");
                byte[] requsetBodyByte = requestBody.toString().getBytes("UTF-8");
                //设置请求头
                connection.setRequestProperty("Content-Length", uploadFile.length() + requsetBodyByte.length + "");
                connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=7e324741816d4");
                //获得输出流
                os = connection.getOutputStream();
                //写入信息
                os.write(requsetBodyByte);
                //连接
                connection.connect();
                //读取本地文件并且写入服务器
                is = new FileInputStream(uploadFile);
                int length = 0;
                byte[] bytes = new byte[1024 * 8];
                while ((length = is.read(bytes)) != -1) {
                    os.write(bytes, 0, length);
                }
    
                if (connection.getResponseCode() == 200) {
                    return "上传成功";
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return "上传失败";
        }
    }
    

    相关文章

      网友评论

        本文标题:029_Android Http的基本使用方法

        本文链接:https://www.haomeiwen.com/subject/ezpldctx.html