okhttp、okhttp3使用post方式发送form-data数据
需求描述˃使用okhttp,而非okhttp3代码实现```OkHttpClientclient=newOkHttpClient();JSONObject
需求描述
如题所述
okhttp版本
<dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
<version>2.7.5</version>
</dependency>
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
json.put("b_time", startTime);
json.put("e_time", endTime);
RequestBody body = new FormEncodingBuilder()
.add("dev_id", deviceId)
// .add("json", String.format("{\"b_time\":\"%s\",\"e_time\":\"%s\"}", startTime,endTime)).build();
.add("json", json.toString()).build();
String url = String.format("http://xxxx");
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
String string = response.body().string();
JSONObject jsonObject = JSONObject.parseObject(string);
if (jsonObject.getString("code").equals("0")) {
JSONArray rows = jsonObject.getJSONArray("rows");
return CommonResult.success(rows);
} else {
return CommonResult.failed(jsonObject.getString("msg"));
}
okhttp3版本
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.11.0</version>
</dependency>
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("key1", "value1")
.addFormDataPart("key2", "value2")
.addFormDataPart("file", "filename.txt",
RequestBody.create(MediaType.parse("text/plain"), new File("path/to/file.txt")))
.build();
相关文章
发表评论
评论列表
- 这篇文章还没有收到评论,赶紧来抢沙发吧~