Commit c20c61efe16c7b68ba6ca865aa5c9327566cc3e6
1 parent
cced7bb8
Exists in
master
add upload file method
Showing
1 changed file
with
39 additions
and
0 deletions
Show diff stats
src/main/java/com/taover/util/UtilHttpByOkHttp.java
| 1 | 1 | package com.taover.util; |
| 2 | 2 | |
| 3 | +import java.io.File; | |
| 4 | +import java.io.IOException; | |
| 3 | 5 | import java.io.UnsupportedEncodingException; |
| 4 | 6 | import java.net.URLEncoder; |
| 5 | 7 | import java.nio.charset.Charset; |
| ... | ... | @@ -18,10 +20,14 @@ import javax.net.ssl.TrustManager; |
| 18 | 20 | import javax.net.ssl.X509TrustManager; |
| 19 | 21 | |
| 20 | 22 | import okhttp3.FormBody; |
| 23 | +import okhttp3.Headers; | |
| 21 | 24 | import okhttp3.MediaType; |
| 25 | +import okhttp3.MultipartBody; | |
| 22 | 26 | import okhttp3.OkHttpClient; |
| 23 | 27 | import okhttp3.Request; |
| 24 | 28 | import okhttp3.RequestBody; |
| 29 | +import okhttp3.Response; | |
| 30 | +import okhttp3.ResponseBody; | |
| 25 | 31 | |
| 26 | 32 | public class UtilHttpByOkHttp { |
| 27 | 33 | public static final String METHOD_GET = "GET"; |
| ... | ... | @@ -146,6 +152,39 @@ public class UtilHttpByOkHttp { |
| 146 | 152 | return builder.build(); |
| 147 | 153 | } |
| 148 | 154 | |
| 155 | + | |
| 156 | + /** | |
| 157 | + * | |
| 158 | + * @param url 请求地址 | |
| 159 | + * @param filePath 文件路径 | |
| 160 | + * @param fileName 文件名 | |
| 161 | + * @param fileKey 表单上传文件对应的key值 | |
| 162 | + * @param header 请求头 | |
| 163 | + * @return 只发post请求 | |
| 164 | + * @throws Exception | |
| 165 | + */ | |
| 166 | + public static ResponseBody sendPostFile(String url, String filePath, String fileName,String fileKey,Map<String, String> header) throws Exception { | |
| 167 | + OkHttpClient client = new OkHttpClient(); | |
| 168 | + RequestBody requestBody = new MultipartBody.Builder() | |
| 169 | + .setType(MultipartBody.FORM) | |
| 170 | + .addFormDataPart(fileKey, fileName, | |
| 171 | + RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath))) | |
| 172 | + .build(); | |
| 173 | + | |
| 174 | + Request request = new Request.Builder() | |
| 175 | + .headers(Headers.of(header)) | |
| 176 | + .url(url) | |
| 177 | + .post(requestBody) | |
| 178 | + .build(); | |
| 179 | + | |
| 180 | + Response response = client.newCall(request).execute(); | |
| 181 | + if (!response.isSuccessful()){ | |
| 182 | + throw new IOException("Unexpected code " + response); | |
| 183 | + } | |
| 184 | + return response.body(); | |
| 185 | + } | |
| 186 | + | |
| 187 | + | |
| 149 | 188 | static TrustManager[] trustAllCerts = new TrustManager[]{ |
| 150 | 189 | new X509TrustManager() { |
| 151 | 190 | public java.security.cert.X509Certificate[] getAcceptedIssuers() { | ... | ... |