android okhttp加公共参数,Android OKHttp添加参数

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

//request

Request.Builder requestBuilder = new Request.Builder()

.url(url);

I've managed the add header but not params.

解决方案

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

你可能感兴趣的:(android,okhttp加公共参数)