From c20c61efe16c7b68ba6ca865aa5c9327566cc3e6 Mon Sep 17 00:00:00 2001 From: gaoming Date: Mon, 16 Sep 2019 20:01:42 +0800 Subject: [PATCH] add upload file method --- src/main/java/com/taover/util/UtilHttpByOkHttp.java | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+), 0 deletions(-) diff --git a/src/main/java/com/taover/util/UtilHttpByOkHttp.java b/src/main/java/com/taover/util/UtilHttpByOkHttp.java index f6991bb..693f71d 100644 --- a/src/main/java/com/taover/util/UtilHttpByOkHttp.java +++ b/src/main/java/com/taover/util/UtilHttpByOkHttp.java @@ -1,5 +1,7 @@ package com.taover.util; +import java.io.File; +import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.Charset; @@ -18,10 +20,14 @@ import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.FormBody; +import okhttp3.Headers; import okhttp3.MediaType; +import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; public class UtilHttpByOkHttp { public static final String METHOD_GET = "GET"; @@ -146,6 +152,39 @@ public class UtilHttpByOkHttp { return builder.build(); } + + /** + * + * @param url 请求地址 + * @param filePath 文件路径 + * @param fileName 文件名 + * @param fileKey 表单上传文件对应的key值 + * @param header 请求头 + * @return 只发post请求 + * @throws Exception + */ + public static ResponseBody sendPostFile(String url, String filePath, String fileName,String fileKey,Map header) throws Exception { + OkHttpClient client = new OkHttpClient(); + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart(fileKey, fileName, + RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath))) + .build(); + + Request request = new Request.Builder() + .headers(Headers.of(header)) + .url(url) + .post(requestBody) + .build(); + + Response response = client.newCall(request).execute(); + if (!response.isSuccessful()){ + throw new IOException("Unexpected code " + response); + } + return response.body(); + } + + static TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { -- libgit2 0.21.2