okhttp学习-------post方式实现

在项目应用中常见的http请求方式主要有get,post两种请求方式,常用post方式又有四种不同方式,okhttp对post 方式提供了很好的支持。 在okhttp中,http报文体抽象为RequestBody类,RequestBody既是各类报文body的基类,又是其工厂类,提供了重载的create用于创建RequestBody对象,相关类图如下 对于postbody为Json数据的请求可以直接使用RequestBody的create 方法。

FormBody实现

private long writeOrCountBytes(BufferedSink sink, boolean countBytes) {
    long byteCount = 0L;

    Buffer buffer;
    if (countBytes) {
      buffer = new Buffer();
    } else {
      buffer = sink.buffer();
    }
    //向缓冲区写入key和value值:遵循格式key1=value1&key2=value2...
    for (int i = 0, size = encodedNames.size(); i < size; i++) {
      if (i > 0) 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 = 0L;
    Buffer byteCountBuffer = null;
    if (countBytes) {
      sink = byteCountBuffer = new Buffer();
    }
//循环写入part到缓冲区
    for (int p = 0, 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);//换行

      if (headers != null) {
        for (int h = 0, 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 != -1) {
        sink.writeUtf8("Content-Length: ")
            .writeDecimalLong(contentLength)
            .write(CRLF);
      } else if (countBytes) {
        // We cant measure the bodys size without the sizes of its components.
        byteCountBuffer.clear();
        return -1L;
      }

      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);
经验分享 程序员 微信小程序 职场和发展