在項目應用中常見的http請求方式主要有get,post兩種請求方式,常用post方式又有四種不同方式HTTP常用post請求方式,okhttp對post 方式提供了很好的支援。
在okhttp中,http封包體抽象為RequestBody類,RequestBody既是各類封包body的基類,又是其工廠類,提供了重載的create用于建立RequestBody對象,相關類圖如下
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICdzFWRoRXdvN1LclHdpZXYyd2LcBzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX90TQOhXQq10Mw1mYoZFWlZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39DMyETNzADNyITMyITM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
對于postbody為Json資料的請求可以直接使用RequestBody的create 方法。
FormBody實作
private long writeOrCountBytes(BufferedSink sink, boolean countBytes) {
long byteCount = L;
Buffer buffer;
if (countBytes) {
buffer = new Buffer();
} else {
buffer = sink.buffer();
}
//向緩沖區寫入key和value值:遵循格式key1=value1&key2=value2...
for (int i = , size = encodedNames.size(); i < size; i++) {
if (i > ) buffer.writeByte('&');
buffer.writeUtf8(encodedNames.get(i));
buffer.writeByte('=');
buffer.writeUtf8(encodedValues.get(i));
}
if (countBytes) {
byteCount = buffer.size();
buffer.clear();
}
return byteCount;
}
2.MultiPartBody實作代碼(參考表單送出的格式定義)
private long writeOrCountBytes(BufferedSink sink, boolean countBytes) throws IOException {
long byteCount = ;
Buffer byteCountBuffer = null;
if (countBytes) {
sink = byteCountBuffer = new Buffer();
}
//循環寫入part到緩沖區
for (int p = , partCount = parts.size(); p < partCount; p++) {
Part part = parts.get(p);
Headers headers = part.headers;
RequestBody body = part.body;
sink.write(DASHDASH);//{':', ' '}
sink.write(boundary);//part分割标記
sink.write(CRLF);//換行\r\n
if (headers != null) {
for (int h = , headerCount = headers.size(); h < headerCount; h++) {
sink.writeUtf8(headers.name(h))
.write(COLONSPACE)//{':', ' '}
.writeUtf8(headers.value(h))
.write(CRLF);
}
}
MediaType contentType = body.contentType();
if (contentType != null) {
sink.writeUtf8("Content-Type: ")
.writeUtf8(contentType.toString())
.write(CRLF);
}
long contentLength = body.contentLength();
if (contentLength != -) {
sink.writeUtf8("Content-Length: ")
.writeDecimalLong(contentLength)
.write(CRLF);
} else if (countBytes) {
// We can't measure the body's size without the sizes of its components.
byteCountBuffer.clear();
return -;
}
sink.write(CRLF);
if (countBytes) {
byteCount += contentLength;
} else {
body.writeTo(sink);
}
sink.write(CRLF);
}
sink.write(DASHDASH);
sink.write(boundary);
sink.write(DASHDASH);
sink.write(CRLF);
if (countBytes) {
byteCount += byteCountBuffer.size();
byteCountBuffer.clear();
}
return byteCount;
}
3.建立Json格式的RequestBody對象
JSONbject json= createJson();
RequestBody body=RequestBody.create(MediaType.parse("application/json"),json.toJsonString);