HTTP超文本传输协议
主要特点 1支持客户/服务器模式 2简单快速 3灵活 4无连接 5无状态
GET请求 POST请求区别
(1)post请求更安全(不会作为url的一部分,不会被缓存、保存在服务器日志、以及浏览器浏览记录中,get请求的是静态资源,则会缓存,如果是数据,则不会缓存)
(2)post请求发送的数据更大(get请求有url长度限制,http协议本身不限制,请求长度限制是由浏览器和web服务器决定和设置)
(3)post请求能发送更多的数据类型(get请求只能发送ASCII字符)
(4)传参方式不同(get请求参数通过url传递,post请求放在request body中传递)
(5)get请求产生一个TCP数据包;post请求产生两个TCP数据包(get请求,浏览器会把http header和data一并发送出去,服务器响应200返回数据;post请求,浏览器先发送header,服务器响应100 continue,浏览器再发送data,服务器响应200 返回数据)
注意:在发送 POST 的时候都没有带 Expect 头,server 也自然不会发 100 continue。
post请求的过程:
(1)浏览器请求tcp连接(第一次握手)
(2)服务器答应进行tcp连接(第二次握手)
(3)浏览器确认,并发送post请求头(第三次握手,这个报文比较小,所以http会在此时进行第一次数据发送)
(4)服务器返回100 Continue响应
(5)浏览器发送数据
(6)服务器返回200 OK响应
get请求的过程:
(1)浏览器请求tcp连接(第一次握手)
(2)服务器答应进行tcp连接(第二次握手)
(3)浏览器确认,并发送get请求头和数据(第三次握手,这个报文比较小,所以http会在此时进行第一次数据发送)
(4)服务器返回200 OK响应
网络环境好的情况下,发一次包和发两次包的时间差别基本可以忽略。而在网络环境差的情况下,两次包的TCP在验证数据包完整性上,有非常大的优点。
GET请求
异步任务类
package com.bw.day1.utile;
import android.os.AsyncTask;
import android.util.Log;
import com.bw.day1.entity.FoodEntity;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MyTask extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... strings) {
return Httputile.getInstance().getString(strings[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
FoodEntity foodEntity = new Gson().fromJson(s, FoodEntity.class);
for (FoodEntity.DataDTO datum : foodEntity.getData()) {
Log.i("title", "-------"+datum.getTitle());
}
}
}
单例
package com.bw.day1.utile;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Httputile {
private Httputile(){}
private static Httputile httputile=null;
public static Httputile getInstance(){
if(httputile==null){
httputile=new Httputile();
}
return httputile;
}
public String getString(String urll){
try {
URL url = new URL(urll);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(2000);
httpURLConnection.setReadTimeout(2000);
httpURLConnection.connect();
if(httpURLConnection.getResponseCode() == 200) {
// InputStream inputStream = httpURLConnection.getInputStream();
// BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
// StringBuilder stringBuilder = new StringBuilder();
// String res="";
// while ((res = bufferedReader.readLine()) != null){
// stringBuilder.append(res);
// }
// return stringBuilder.toString();
InputStream inputStream = httpURLConnection.getInputStream();
byte[] bytes = new byte[1024];
int len=0;
StringBuilder stringBuilder = new StringBuilder();
while ((len = inputStream.read(bytes)) !=-1){
stringBuilder.append(new String(bytes, 0, len));
}
return stringBuilder.toString();
}
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
}
POST请求
package com.bw.day1.utile;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Httputile {
private Httputile(){}
private static Httputile httputile=null;
public static Httputile getInstance(){
if(httputile==null){
httputile=new Httputile();
}
return httputile;
}
//GET请求
public String GetString(String urll){
try {
URL url = new URL(urll);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(2000);
httpURLConnection.setReadTimeout(2000);
httpURLConnection.connect();
if(httpURLConnection.getResponseCode() == 200) {
// InputStream inputStream = httpURLConnection.getInputStream();
// BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
// StringBuilder stringBuilder = new StringBuilder();
// String res="";
// while ((res = bufferedReader.readLine()) != null){
// stringBuilder.append(res);
// }
// return stringBuilder.toString();
InputStream inputStream = httpURLConnection.getInputStream();
byte[] bytes = new byte[1024];
int len=0;
StringBuilder stringBuilder = new StringBuilder();
while ((len = inputStream.read(bytes)) !=-1){
stringBuilder.append(new String(bytes, 0, len));
}
return stringBuilder.toString();
}
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
//POST请求
public String PostString(String urll, String params){
try {
URL url = new URL(urll);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setReadTimeout(2000);
httpURLConnection.setConnectTimeout(2000);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(params.getBytes());
outputStream.flush();//刷新
if(httpURLConnection.getResponseCode()==200){
InputStream inputStream = httpURLConnection.getInputStream();
byte[] bytes = new byte[1024];
StringBuilder stringBuilder = new StringBuilder();
int len=0;
while ((len=inputStream.read(bytes))!=-1){
stringBuilder.append(new String(bytes,0,len));
}
return stringBuilder.toString();
}
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
}
异步任务
package com.bw.day1.utile;
import android.os.AsyncTask;
import android.util.Log;
import com.bw.day1.entity.FoodEntity;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MyTask extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... strings) {
//return Httputile.getInstance().GetString(strings[0]);//get请求
//POST请求
String path= strings[0];
String params= strings[1];
String s = Httputile.getInstance().PostString(path, params);
Log.i("title", "-------"+s);
return s;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
FoodEntity foodEntity = new Gson().fromJson(s, FoodEntity.class);
}
}
下载
public void download(String url){
try {
URL url1 = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url1.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(2000);
httpURLConnection.setReadTimeout(2000);
httpURLConnection.connect();
if(httpURLConnection.getResponseCode()==200){
InputStream inputStream = httpURLConnection.getInputStream();
byte[] bytes = new byte[1024];
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File file = new File("/sdcard/zt.jpg");
FileOutputStream fileOutputStream = new FileOutputStream(file);
int len =0;
int max=httpURLConnection.getContentLength();
int pos=0;
while ((len = inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes, 0, len);
pos+=len;
}
}
}
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
上传
//上传
public void Upload(String urlpath,String filepath){
String BOUNDARY = UUID.randomUUID().toString();
String PREFIX ="--",LINE_END="\r\n";
String CONTENT_TYPE = "multipart/form-data";
try {
//Post 上传服务器请求配置,特殊要求
URL url = new URL(urlpath);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
httpURLConnection.setReadTimeout(5000);
httpURLConnection.connect();
File file = new File(filepath);
if(file!=null){
OutputStream outputStream = httpURLConnection.getOutputStream();
StringBuffer stringBuffer = new StringBuffer();
//真正的数据流发送前进行边界设置
stringBuffer.append(PREFIX);
stringBuffer.append(BOUNDARY);
stringBuffer.append(LINE_END);
stringBuffer.append("Content-Disposition: form-data; name=\"file\"; filename=\""+file.getName()+"\""+LINE_END);
stringBuffer.append(LINE_END);
outputStream.write(stringBuffer.toString().getBytes());
//真正的数据流部分
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len=0;
while ((len=fileInputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
fileInputStream.close();
//真正数据流完毕需要设定结尾标记
outputStream.write(LINE_END.getBytes());
byte[] enddata=(PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
outputStream.write(enddata);
outputStream.flush();
if(httpURLConnection.getResponseCode()==200){
}
}
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}