【问题标题】:Android OKHttp adding paramsAndroid OKHttp 添加参数
【发布时间】:2015-06-30 00:20:56
【问题描述】:

如何将参数附加到 OkHttp Request.builder 中?

//request
Request.Builder requestBuilder = new Request.Builder()
            .url(url);

我已经管理了添加标题,但没有管理参数。

【问题讨论】:

    标签: android okhttp


    【解决方案1】:

    这里有一个完整的例子,说明如何使用 okhttp 发出 post 请求(okhttp3)。

    将数据作为表单正文发送

    RequestBody formBody = new FormBody.Builder()
            .add("param_a", "value_a")
            .addEncoded("param_b", "value_b")
            .build();
    

    将数据作为多部分发送

    RequestBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("fieldName", fileToUpload.getName(),RequestBody.create(MediaType.parse("application/octet-stream"), fileToUpload))
                .build();
    

    以 json body 形式发送数据

        RequestBody jsonBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
    

    现在创建请求

        Request request = new Request.Builder()
                .addHeader("header_a", "value_a")  // to add header data
                .post(formBody)         // for form data
                .post(jsonBody)         // for json data
                .post(multipartBody)    // for multipart data
                .build();
    
        Response response = client.newCall(request).execute();
    

    ** fileToUpload 是 java File 类型的对象

    ** 客户端是 OkHttpClient 类型的对象

    【讨论】:

      【解决方案2】:

      也许你的意思是这样的:

       HttpUrl url = new HttpUrl.Builder().scheme("http").host(HOST).port(PORT)
                  .addPathSegment("xxx").addPathSegment("xxx")
                  .addQueryParameter("id", "xxx")
                  .addQueryParameter("language", "xxx").build();
      

      【讨论】:

        【解决方案3】:

        你可以使用这个库:https://github.com/square/mimecraft:

        FormEncoding fe = new FormEncoding.Builder()
            .add("name", "Lorem Ipsum")
            .add("occupation", "Filler Text")
            .build();
        

        多部分内容:

        Multipart m = new Multipart.Builder()
            .addPart(new Part.Builder()
                .contentType("image/png")
                .body(new File("/foo/bar/baz.png"))
                .build())
            .addPart(new Part.Builder()
                .contentType("text/plain")
                .body("The quick brown fox jumps over the lazy dog.")
                .build())
            .build();
        

        请看这里: How to use OKHTTP to make a post request?

        【讨论】:

        • 如何将两者结合起来?
        • 你的意思是参数和标题吗?
        • 查询URL上的参数?
        猜你喜欢
        • 1970-01-01
        • 2014-08-05
        • 2018-01-04
        • 2016-03-01
        • 2017-05-07
        • 2015-07-20
        • 2015-12-31
        • 2015-05-12
        • 1970-01-01
        相关资源
        最近更新 更多