Android OKHttp adding params

后端 未结 3 1580
旧巷少年郎
旧巷少年郎 2020-12-10 23:24

How is it possible to append params to an OkHttp Request.builder?

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


        
相关标签:
3条回答
  • 2020-12-10 23:58

    You can use this lib: https://github.com/square/mimecraft:

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

    Multipart content:

    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();
    

    See here: How to use OKHTTP to make a post request?

    0 讨论(0)
  • 2020-12-11 00:08

    Here is a complete example on how to use okhttp to make post request (okhttp3).

    To send data as form body

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

    To send data as multipart body

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

    To send data as json body

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

    Now create request

        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 is a object of type java File

    ** client is a object of type OkHttpClient

    0 讨论(0)
  • 2020-12-11 00:19

    Maybe you mean this:

     HttpUrl url = new HttpUrl.Builder().scheme("http").host(HOST).port(PORT)
                .addPathSegment("xxx").addPathSegment("xxx")
                .addQueryParameter("id", "xxx")
                .addQueryParameter("language", "xxx").build();
    
    0 讨论(0)
提交回复
热议问题