您的位置:首页 > 理论基础 > 计算机网络

http协议介绍+文件的上传和下载

2019-08-02 21:29 232 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/liuguitong_BK/article/details/98240337

http协议介绍:

HTTP,超文本传输协议,英文全称是Hypertext Transfer Protocol,它是互联网上应用最为广泛的一种网络协议。HTTP是一种应用层协议,它是基于TCP协议之上的请求/响应式的协议,即一个客户端与服务器建立连接后,向服务器发送一个请求;服务器接到请求后,给予相应的响应信息

请求协议和响应协议

请求协议:
①请求首行:
②请求头信息:客户端告诉服务器我这边的信息
③空行
④请求体:get请求是没有请求体的
响应协议:
①响应首行:HTTP/1.1 200 OK
②响应头信息:Content-Length 服务器返回数据的总大小
③空行
④响应体:服务器返回的数据

8种请求方式:

1、OPTIONS
返回服务器针对特定资源所支持的HTTP请求方法,也可以利用向web服务器发送‘*’的请求来测试服务器的功能性
2、HEAD
向服务器索与GET请求相一致的响应,只不过响应体将不会被返回。这一方法可以再不必传输整个响应内容的情况下,就可以获取包含在响应小消息头中的元信息。
3、GET
向特定的资源发出请求。它本质就是发送一个请求来取得服务器上的某一资源。资源通过一组HTTP头和呈现数据(如HTML文本,或者图片或者视频等)返回给客户端。
4、POST
向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。
5、PUT
向指定资源位置上传其最新内容
6、DELETE
请求服务器删除Request-URL所标识的资源
7、TRACE
回显服务器收到的请求,主要用于测试或诊断
8、CONNECT
HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器。

get请求和post请求的区别

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

Http1.0和http1.1的区别

http1.0是非持续连接 Http1.1是长久持续连接

网络七层

应用层:应用程序,用户看的见 http协议
表示层:将人看的懂的转成计算机看的懂
会话层:发起一个连接
传输层:规定传输协议和端口号 tcp协议 udp协议
网络层:规定网络ip ip协议
数据链路层:
物理层:光缆、网线

文件的上传和下载(加权限)

文件断点续传


Java代码

public class Main2Activity extends Activity implements View.OnClickListener {
private ProgressBar pro;

int start = 0;
int end = 0;
int sum = 0;
boolean isDown = true;

Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);

switch (msg.what) {
case 1:
pro.setProgress((int) Math.floor(sum / 1000));
break;
case 2:
pro.setMax((int) Math.floor(end / 1000));
break;

}
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
pro = (ProgressBar) findViewById(R.id.pro);

findViewById(R.id.start).setOnClickListener(this);
findViewById(R.id.pause).setOnClickListener(this);

}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
isDown = true;
Toast.makeText(Main2Activity.this, "开始下载", Toast.LENGTH_SHORT).show();
getUrlSize("http://qiubai-video.qiushibaike.com/VGU6K0T3CDU6N7JJ_3g.mp4");

break;
case R.id.pause:
isDown = false;
Toast.makeText(Main2Activity.this, "已暂停", Toast.LENGTH_SHORT).show();
break;
}
}

public void getUrlSize(final String string) {
new Thread(new Runnable() {
@Override
public void run() {
URL url = null;
try {
url = new URL(string);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

end = connection.getContentLength();
Message obtain = Message.obtain();
obtain.what = 2;
handler.sendMessage(obtain);
new MyThread().start();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}).start();
}

class MyThread extends Thread {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void run() {
super.run();
try {
URL url = new URL("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setRequestProperty("Range", "bytes=" + start + "-" + end);
connection.setDoInput(true);
connection.setDoOutput(true);

String path = Environment.getExternalStorageDirectory().getPath() + "/a1705.mp4";
RandomAccessFile file = new RandomAccessFile(path, "rw");
file.seek(sum);
InputStream inputStream = null;
if (connection.getResponseCode() == 206) {

inputStream = connection.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
file.write(bytes, 0, len);
sum += len;

Message obtain1 = Message.obtain();
obtain1.what = 1;
handler.sendMessage(obtain1);
if (sum == end) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(Main2Activity.this, "下载完成", Toast.LENGTH_SHORT).show();
}
});
isDown = false;

7ff7
}

if (!isDown) {
start = sum;
break;
}
}

}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}
}

文件的上传

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void click(View view)
{
new Thread()
{
@Override
public void run() {
super.run();
upload();
}
}.start();
}

/**
* 上传
*
*/
public void upload() {

String boundStr = "*****";
String begin = "--";
String end = "\r\n";

try {
URL url = new URL("http://169.254.112.39:80/Service/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
//            /mnt/sdcard/http.txt
connection.setRequestProperty("Connection","Keep-Alive"); //设置长连接
//设置内容类型
connection.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundStr);

DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
String fileName = "http.txt";
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(begin+boundStr+end)
.append("Content-Disposition: form-data; name=\"file\"; filename=\""+fileName+"\""+"\r\n")
.append(end);

outputStream.write(stringBuffer.toString().getBytes());

String filePath = "/mnt/sdcard/http.txt";
FileInputStream fileInputStream = new FileInputStream(filePath);
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1)
{
outputStream.write(bytes,0,len);
}

outputStream.writeBytes(end);
outputStream.writeBytes(begin+boundStr+begin+end);
outputStream.flush();

String resultStr = connection.getResponseMessage();
if(resultStr != null)
{
Log.e("=================", "success");
}

fileInputStream.close();
outputStream.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

}

文件下载

public static void download(String url,String path)  {
FileOutputStream fileOutputStream = null;
InputStream inputStream=null;
try {
URL url1 = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
if(urlConnection.getResponseCode()==200){
inputStream = urlConnection.getInputStream();
fileOutputStream = new FileOutputStream(path);
byte[] bytes=new byte[1024];
int len=0;
while((len=inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len);
}
}

} catch (IOException e) {
e.printStackTrace();
} finally {//关流
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: