okhttp上傳檔案和攜帶引數
阿新 • • 發佈:2019-02-13
一個小工具類用來post json字串和檔案上傳並且帶引數外加忽略https證書認證
1 上傳檔案和引數
public class NetWorkUtilsHttps { public static final MediaType JSON = MediaType .parse("application/json; charset=utf-8"); private OkHttpClient client; private SSLContext sslContext = null; public NetWorkUtilsHttps() { X509TrustManager xtm = newX509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Overridepublic X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; try { sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch(KeyManagementException e) { e.printStackTrace(); } HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; client = new OkHttpClient.Builder() .sslSocketFactory(sslContext.getSocketFactory()) .readTimeout(50, TimeUnit.SECONDS) .connectTimeout(50, TimeUnit.SECONDS) .hostnameVerifier(DO_NOT_VERIFY) .build(); } //post json
.addHeader("code", trsCode)
是加頭部的一些引數public String post(String json, String code, String url) { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .addHeader("code", trsCode).post(body).build(); try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } response.body().close(); } catch (IOException e) { e.printStackTrace(); } return "{\"ROOT\":{\"BODY\":{\"info\":[]},\"HEAD\":{\"resCode\":\"545\",\"TrsAppType\":\"1\",\"resMsg\":\"連線伺服器失敗,請稍後重試!\"}}}"; } public String uploadFile(File file, String uniqueNo, String fileCode, String path) { StringBuffer resultBuffer = new StringBuffer(""); Map<String, String> params = new HashMap<>(); params.put("busiType", "0");//業務型別params.put("flag", "up");// 操作標誌:up-上傳 down-下載params.put("fileType", fileCode);//檔案所屬型別 code碼 引數MultipartBody.Builder form = new MultipartBody.Builder().setType(MultipartBody.FORM); StringBuffer buffer = new StringBuffer(); String url = path; url += "?"; for (String key : params.keySet()) { //新增引數buffer.append(key + "=" + params.get(key) + "&"); Log.e(key, params.get(key)); } url += buffer.toString(); if (url.lastIndexOf("&") != -1) { url = url.substring(0, url.lastIndexOf("&"));//拼接引數 }
//放檔案 form.addPart(Headers.of("Content-Disposition", "form-data; name=\"file\";filename=\"" + file.getName() + "\""), RequestBody.create(MediaType.parse("image/png"), file)); RequestBody body = form.build(); Request request = new Request .Builder() .url(url) .addHeader("Connection", "keepAlive") .addHeader("Charset", "UTF-8") .post(body) .build(); try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { resultBuffer.replace(0, resultBuffer.length(), response.body().string()); Log.e("upFileFlag", resultBuffer.toString()); return resultBuffer.toString(); } else { Log.e("error", response.body().string()); } response.body().close(); } catch (IOException e) { e.printStackTrace(); } return "{\"resCode\":\"099\",\"resMsg\":\"上傳檔案失敗\"}"; } }