上一篇文章已經對http協議和總體框架作了一個大體的介紹: 手寫Android網絡框架——CatHttp(一)git
這篇文章咱們主要就分析下具體子類是如何實現,以什麼方式構建成能夠被服務器識別並接受的數據類型提交上去的。因此這篇文章咱們主要討論正文的數據類型和格式。github
並非每種請求方式都能攜帶正文,如post和put能夠攜帶正文,而get和delete不能攜帶正文,有參數的話直接拼接在url後面。而不一樣的正文類型對應的一個請求頭(Content-Type)是不一樣的,Http協議根據這個請求頭按照對應的類型去解析正文。bash
若是正文傳入的是表單,那麼請求頭聲明的ContentType爲:服務器
application/x-www-form-urlencoded; charset=UTF-8網絡
表單組織的結構格式爲:app
username=zhangsan&pwd=12345&date=2015框架
也就是當二者均知足該要求時,服務器能夠正常解析表單裏的數據。dom
在最初的 http 協議中,沒有上傳文件方面的功能。 rfc1867爲 http 協議添加了這個功能。異步
若是想傳輸文件或者一組二進制字節,則請求頭聲明的Content-Type聲明爲:ide
"multipart/from-data; boundary=" + boundary;
其中boundary是一個隨機數,在下面的正文格式中會使用該boundary做爲標識:
--AaB03x
Content-Disposition: form-data; name="field1"
Joe Blow
--AaB03x
Content-Disposition: form-data; name="pics"; filename="file1.txt"
Content-Type: text/plain
... contents of file1.txt ...
--AaB03x--
複製代碼
能夠看到,其實Multipart的方式也同時支持傳輸鍵值對,只是構造的方式不同,每個(部分) ,姑且稱爲部分,都是以--boundary開始的,而且後面跟着相似請求頭的鍵值對,用來講明數據類型,每部分的數據正文跟這種「請求頭」分隔開。
瞭解了不一樣正文的格式,咱們就能夠實現咱們的子類了。
針對於文件這種格式會比較複雜,可是觀察會有一個共同點,也就是咱們說的「部分」,這裏用Part表示,下面先看具體的http任務是怎麼執行的
能夠看到,實際的Call實際無論是同步仍是異步,都是調用了HttpThreadPool提供的結構來執行Task,從而調度任務的執行的。
public class HttpCall implements Call {
final Request request;
final CatHttpClient.Config config;
private IRequestHandler requestHandler = new RequestHandler();
public HttpCall(CatHttpClient.Config config, Request request) {
this.config = config;
this.request = request;
}
@Override
public Response execute() {
Callable<Response> task = new SyncTask();
Response response;
try {
response = HttpThreadPool.getInstance().submit(task);
return response;
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return new Response.Builder()
.code(400)
.message("線程異常中斷")
.body(new ResponseBody(null))
.build();
}
@Override
public void enqueue(Callback callback) {
Runnable runnable = new HttpTask(this, callback, requestHandler);
HttpThreadPool.getInstance().execute(new FutureTask<>(runnable, null));
}
/**
* 同步提交Callable
*/
class SyncTask implements Callable<Response> {
@Override
public Response call() throws Exception {
Response response = requestHandler.handlerRequest(HttpCall.this);
return response;
}
}
}
複製代碼
RequestHandler 是網絡請求的處理者,將請求的Request解析成標準的Http格式的請求提交給服務器並獲取服務器返回的內容。
public class RequestHandler implements IRequestHandler {
@Override
public Response handlerRequest(HttpCall call) throws IOException {
HttpURLConnection connection = mangeConfig(call);
if (!call.request.heads.isEmpty()) addHeaders(connection, call.request);
if (call.request.body != null) writeContent(connection, call.request.body);
if (!connection.getDoOutput()) connection.connect();
//解析返回內容
int responseCode = connection.getResponseCode();
if (responseCode >= 200 && responseCode < 400) {
byte[] bytes = new byte[1024];
int len;
InputStream ins = connection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = ins.read(bytes)) != -1) {
baos.write(bytes, 0, len);
}
Response response = new Response
.Builder()
.code(responseCode)
.message(connection.getResponseMessage())
.body(new ResponseBody(baos.toByteArray()))
.build();
try {
ins.close();
connection.disconnect();
} finally {
if (ins != null) ins.close();
if (connection != null) connection.disconnect();
}
return response;
}
throw new IOException(String.valueOf(connection.getResponseCode()));
}
/**
* 用
*
* @param connection
* @param body
* @throws IOException
*/
private void writeContent(HttpURLConnection connection, RequestBody body) throws IOException {
OutputStream ous = connection.getOutputStream();
body.writeTo(ous);
}
/**
* HttpUrlConnection基本參數的配置
*
* @param call
* @return
* @throws IOException
*/
private HttpURLConnection mangeConfig(HttpCall call) throws IOException {
URL url = new URL(call.request.url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(call.config.connTimeout);
connection.setReadTimeout(call.config.readTimeout);
connection.setDoInput(true);
if (call.request.body != null && Request.HttpMethod.checkNeedBody(call.request.method)) {
connection.setDoOutput(true);
}
return connection;
}
/**
* 給對象添加請求頭
*
* @param connection
* @param request
*/
private void addHeaders(HttpURLConnection connection, Request request) {
Set<String> keys = request.heads.keySet();
for (String key : keys) {
connection.addRequestProperty(key, request.heads.get(key));
}
}
}
複製代碼
public class Util {
public static void checkMap(String key, String value) {
if (key == null) throw new NullPointerException("key == null");
if (key.isEmpty()) throw new NullPointerException("key is empty");
if (value == null) throw new NullPointerException("value == null");
if (value.isEmpty()) throw new NullPointerException("value is empty");
}
public static void checkMethod(Request.HttpMethod method, RequestBody body) {
if (method == null)
throw new NullPointerException("method == null");
if (body != null && Request.HttpMethod.checkNoBody(method))
throw new IllegalStateException("方法" + method + "不能有請求體");
if (body == null && Request.HttpMethod.checkNeedBody(method))
throw new IllegalStateException("方法" + method + "必須有請求體");
}
/**
* 轉換成file的頭
*
* @param key
* @param fileName
* @return
*/
public static String trans2FileHead(String key, String fileName) {
StringBuilder sb = new StringBuilder();
sb.append(MultipartBody.disposition)
.append("name=")//name=
.append("\"").append(key).append("\"").append(";").append(" ")//"key";
.append("filename=")//filename
.append("\"").append(fileName).append("\"")//"filename"
.append("\r\n");
return sb.toString();
}
/**
* 轉換成表單形式
*
* @param key
* @return
*/
public static String trans2FormHead(String key) {
StringBuilder sb = new StringBuilder();
sb.append(MultipartBody.disposition)
.append("name=")//name=
.append("\"").append(key).append("\"") //"key"
.append("\r\n");//next line
return sb.toString();
}
public static byte[] getUTF8Bytes(String str) throws UnsupportedEncodingException {
return str.getBytes("UTF-8");
}
}
複製代碼
既然表單這種格式比較簡單,咱們就先構建表單,能夠看到,咱們能夠經過建造者的方式能夠直接傳入鍵值對或者map,內部用一個ArrayMap來存儲鍵值對,寫出的時候將map裏的鍵值對按照表單的方式構建好再寫出去。
public class FormBody extends RequestBody {
// 限制參數不要過多(ArrayMap效率,並且不多須要破k的參數)
public static final int MAX_FROM = 1000;
final Map<String, String> map;
public FormBody(Builder builder) {
this.map = builder.map;
}
@Override
public String contentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
@Override
public void writeTo(OutputStream ous) throws IOException {
try {
ous.write(transToString(map).getBytes("UTF-8"));
ous.flush();
} finally {
if (ous != null) {
ous.close();
}
}
}
/**
* 拼接請求參數
*
* @param map
* @return
*/
private String transToString(Map<String, String> map) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
Set<String> keys = map.keySet();
for (String key : keys) {
if (!TextUtils.isEmpty(sb)) {
sb.append("&");
}
sb.append(URLEncoder.encode(key, "UTF-8"));
sb.append("=");
sb.append(URLEncoder.encode(map.get(key), "UTF-8"));
}
return sb.toString();
}
public static class Builder {
private Map<String, String> map;
public Builder() {
map = new ArrayMap<>();
}
public Builder add(String key, String value) {
if (map.size() > MAX_FROM) throw new IndexOutOfBoundsException(" 請求參數過多");
Util.checkMap(key, value);
map.put(key, value);
return this;
}
public Builder map(Map<String, String> map) {
if (map.size() > MAX_FROM) throw new IndexOutOfBoundsException(" 請求參數過多");
this.map = map;
return this;
}
public FormBody build() {
return new FormBody(this);
}
}
}
複製代碼
Part做爲一個抽象類提供了兩個靜態方法用來建立不一樣的對象,一種是鍵值對,另外一種是文件。其中寫出正文的方法按照標準格式來就好了。
public abstract class Part {
private Part() {
}
public abstract String contentType();
public abstract String heads();
public abstract void write(OutputStream ous) throws IOException;
/**
* 建立構建form的part
*
* @param key
* @param value
* @return
*/
public static Part create(final String key, final String value) {
return new Part() {
@Override
public String contentType() {
return null;
}
@Override
public String heads() {
return Util.trans2FormHead(key);
}
@Override
public void write(OutputStream ous) throws IOException {
ous.write(heads().getBytes("UTF-8"));
ous.write(END_LINE);
ous.write(value.getBytes("UTF-8"));
ous.write(END_LINE);
}
};
}
public static Part create(final String type, final String key, final File file) {
if (file == null) throw new NullPointerException("file 爲空");
if (!file.exists()) throw new IllegalStateException("file 不存在");
return new Part() {
@Override
public String contentType() {
return type;
}
@Override
public String heads() {
return Util.trans2FileHead(key, file.getName());
}
@Override
public void write(OutputStream ous) throws IOException {
ous.write(heads().getBytes());
ous.write("Content-Type: ".getBytes());
ous.write(Util.getUTF8Bytes(contentType()));
ous.write(END_LINE);
ous.write(END_LINE);
writeFile(ous, file);
ous.write(END_LINE);
ous.flush();
}
/**
* 寫出文件
* @param ous 輸出流
* @param file 文件
*/
private void writeFile(OutputStream ous, File file) throws IOException {
FileInputStream ins = null;
try {
ins = new FileInputStream(file);
int len;
byte[] bytes = new byte[2048];
while ((len = ins.read(bytes)) != -1) {
ous.write(bytes, 0, len);
}
} finally {
if (ins != null) {
ins.close();
}
}
}
};
}
}
複製代碼
MultipartBody 存儲了一組Part對象,對外提供了兩個接口——傳入鍵值對和傳入文件,同時按照上面Multipart的格式寫出body存儲的全部內容。
public class MultipartBody extends RequestBody {
public static final String disposition = "content-disposition: form-data; ";
public static final byte[] END_LINE = {'\r', '\n'};
public static final byte[] PREFIX = {'-', '-'};
final List<Part> parts;
final String boundary;
public MultipartBody(Builder builder) {
this.parts = builder.parts;
this.boundary = builder.boundary;
}
@Override
public String contentType() {
return "multipart/from-data; boundary=" + boundary;
}
@Override
public void writeTo(OutputStream ous) throws IOException {
try {
for (Part part : parts) {
ous.write(PREFIX);
ous.write(boundary.getBytes("UTF-8"));
ous.write(END_LINE);
part.write(ous);
}
ous.write(PREFIX);
ous.write(boundary.getBytes("UTF-8"));
ous.write(PREFIX);
ous.write(END_LINE);
ous.flush();
} finally {
if (ous != null) {
ous.close();
}
}
}
public static class Builder {
private String boundary;
private List<Part> parts;
public Builder() {
this(UUID.randomUUID().toString());
}
private Builder(String boundary) {
this.parts = new ArrayList<>();
this.boundary = boundary;
}
public Builder addPart(String type, String key, File file) {
if (key == null) throw new NullPointerException("part name == null");
parts.add(Part.create(type, key, file));
return this;
}
public Builder addForm(String key, String value) {
if (key == null) throw new NullPointerException("part name == null");
parts.add(Part.create(key, value));
return this;
}
public MultipartBody build() {
if (parts.isEmpty()) throw new NullPointerException("part list == null");
return new MultipartBody(this);
}
}
}
複製代碼
具體實現類基本如上,這兩篇就是CatHttp的所有內容了,源碼已經放在github上——傳送門,若是有什麼不足之處,歡迎你們指正,若是以爲我寫的還不錯,就關注我吧~