Http的基本使用

应用层 :应用程序,用户看得见的http协议表示层:将人看的懂的转成计算机看的懂会话层:发起一个连接传输层:规定传输协议和端口号 TCP协议,UDP协议网络层:规定网络ip ip协议数据链路层物理层:光缆、网线文件下载(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 "上传失败";
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值