OkHttp使用post请求注意点

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u014053926/article/details/51000659

简单谈谈个人在使用OkHttp过程中发现的注意点:

1.提交键值对

OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException { 

RequestBody formBody = new FormEncodingBuilder()
    .add("platform", "android")
    .add("name", "bug")
    .add("subject", "XXXXXXXXXXXXXXX")
    .build();

Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();

 Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

主要使用FormEncodingBuilder来添加参数值、post url即可

2.上传文件

此处以上传图片为例

protected RequestBody postBody(File file) {
    // 设置请求体
    MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    RequestBody body = MultipartBody.create(MEDIA_TYPE_PNG, file);

    MultipartBody.Builder builder = new MultipartBody.Builder();
    builder.setType(MultipartBody.FORM);
    //这里是 封装上传图片参数
    builder.addFormDataPart("file", file.getName(), body);

    // 封装请求参数,这里最重要
    HashMap<String, String> params = new HashMap<>();
    params.put("client","Android");
    params.put("uid","1061");
    params.put("token","1911173227afe098143caf4d315a436d");
    params.put("uuid","A000005566DA77");
    //参数以添加header方式将参数封装,否则上传参数为空
    if (params != null && !params.isEmpty()) {
        for (String key : params.keySet()) {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
            RequestBody.create(null, params.get(key)));
        }
    }
    return builder.build();
展开阅读全文

没有更多推荐了,返回首页