当前位置: 代码迷 >> 综合 >> okHttp3 实现post请求提交字符串、键值对、上传文件
  详细解决方案

okHttp3 实现post请求提交字符串、键值对、上传文件

热度:213   发布时间:2023-11-01 09:32:23.0

一、post提交json字符串

public String test() throws Exception {
    OkHttpClient okHttpClient = new OkHttpClient();MediaType json = MediaType.parse("application/json; charset=utf-8");RequestBody body = RequestBody.create(json, "json字符串");Request request = new Request.Builder().post(body).url("请求的url").build();Response response = okHttpClient.newCall(request).execute();if(!response.isSuccessful()) {
    log.info("请求失败");// 一般会在这抛个异常}String result = response.body().string();response.body().close();return reslut;
}

二、post提交键值对

public String test() throws Exception {
    OkHttpClient okHttpClient = new OkHttpClient();FormBody formBody = new FormBody.Builder().add("参数名1", "参数1").add("参数名2", "参数2").build();Request request = new Request.Builder().url("请求的url").post(formBody).build();Response response = okHttpClient.newCall(request).execute();if(!response.isSuccessful()) {
    log.info("请求失败");// 一般会在这抛个异常}String result = response.body().string();response.body().close();return reslut;
}

三、上传文件

public String test() throws Exception {
    OkHttpClient okHttpClient = new OkHttpClient();// file是要上传的文件 File()RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);// 不仅可以支持传文件,还可以在传文件的同时,传参数MultipartBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("参数名1", "参数1").addFormDataPart("接收文件的参数名", "文件名", fileBody).build();Request request = new Request.Builder().url("请求的url").post(requestBody).build();Response response = okHttpClient.newCall(request).execute();if(!response.isSuccessful()) {
    log.info("请求失败");// 一般会在这抛个异常}String result = response.body().string();response.body().close();return reslut;
}

四、报错java.net.SocketTimeoutException: timeout

报这个错,说明请求超时了,可以给它设置个时长120秒,如果还超时,可以再设长一点

// 将原本的这一行替换一下
// Response response = okHttpClient.newCall(request).execute();
// .connectTimeout(120, TimeUnit.SECONDS) 设置连接超时时长为120秒
// .readTimeout(120, TimeUnit.SECONDS) 设置读取超时时长为120秒
// .writeTimeout(120, TimeUnit.SECONDS) 设置写入超时时长为120秒
Response response = okHttpClient.newBuilder().connectTimeout(120, TimeUnit.SECONDS).readTimeout(120, TimeUnit.SECONDS).writeTimeout(120, TimeUnit.SECONDS).build().newCall(request).execute();
  相关解决方案