【发布时间】:2015-06-30 00:20:56
【问题描述】:
如何将参数附加到 OkHttp Request.builder 中?
//request
Request.Builder requestBuilder = new Request.Builder()
.url(url);
我已经管理了添加标题,但没有管理参数。
【问题讨论】:
如何将参数附加到 OkHttp Request.builder 中?
//request
Request.Builder requestBuilder = new Request.Builder()
.url(url);
我已经管理了添加标题,但没有管理参数。
【问题讨论】:
这里有一个完整的例子,说明如何使用 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 类型的对象
【讨论】:
也许你的意思是这样的:
HttpUrl url = new HttpUrl.Builder().scheme("http").host(HOST).port(PORT)
.addPathSegment("xxx").addPathSegment("xxx")
.addQueryParameter("id", "xxx")
.addQueryParameter("language", "xxx").build();
【讨论】:
你可以使用这个库: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();
【讨论】: