CloseableHttpClient https上傳文件與form

//上傳form表單public String download(String urlStr, String filePath, String uploadTime,String batchFileName, String downloadPassword) {try {List params = new ArrayList();params.add(new BasicNameValuePair("uploadTime", uploadTime));params.add(new BasicNameValuePair("batchFileName", batchFileName));params.add(new BasicNameValuePair("downloadPassword", downloadPassword));RequestConfig config = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).setConnectionRequestTimeout(30000).build();HttpClientBuilder clientBuilder = HttpClients.custom();clientBuilder.setDefaultRequestConfig(config);KeyStore kstore = KeyStore.getInstance(SSLEntity.caType);kstore.load(new FileInputStream(SSLEntity.filePath),SSLEntity.password.toCharArray());KeyManagerFactory keyFactory = KeyManagerFactory.getInstance("SunX509");keyFactory.init(kstore, SSLEntity.password.toCharArray());TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("TLSv1");sslContext.init(keyFactory.getKeyManagers(), tm, null);SSLConnectionSocketFactory ssl = new SSLConnectionSocketFactory(sslContext,new String[] { "TLSv1" }, null,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);if (ssl != null)clientBuilder.setSSLSocketFactory(ssl);CloseableHttpClient client = clientBuilder.build(); CloseableHttpResponse response = null; RequestConfig requestConfig = RequestConfig.copy(config).build(); HttpPost httpPost = new HttpPost(urlStr); if(httpPost != null) { if(params != null && params.size() > 0) httpPost.setEntity(new UrlEncodedFormEntity(params, isEmpty(null) ? "utf-8" : null)); httpPost.setConfig(requestConfig); response = client.execute(httpPost); } boolean status = response.getStatusLine().getStatusCode() == 200; String fileName = ""; if(status){ Header headers[] = response.getHeaders("Content-disposition"); String headersFileName = headers[0].getValue(); String strInfo[] = headersFileName.split("\\|"); String suffixs[] = headersFileName.replaceAll("\"", "").split("\\."); if(suffixs.length < 2) { String jsonInfo = strInfo[0].split("\\=")[1]; return URLDecoder.decode(jsonInfo, "UTF-8"); } File path = new File(filePath); if(!path.exists()) path.mkdirs(); fileName = (new StringBuilder(String.valueOf(filePath))).append(filePath.endsWith(File.separator) ? "" : File.separator).append(strInfo[1].split("\\=")[1]).toString(); HttpEntity entity = response.getEntity(); if(entity != null) { InputStream in1 = entity.getContent(); File file = new File(fileName); FileOutputStream fout1 = new FileOutputStream(file); int ret = -1; byte tmp[] = new byte[1024]; while((ret = in1.read(tmp)) != -1) fout1.write(tmp, 0, ret); fout1.flush(); fout1.close(); Result.toSuccessJson((new StringBuilder("回盤文件已經下載,地址:")).append(fileName).toString()); EntityUtils.consume(entity); } }} catch (Exception e) {e.printStackTrace();return Result.toFailedJson(e.getMessage());}return Result.toSuccessJson("批量文件下載成功");}//上傳文件@SuppressWarnings("deprecation")public String send(String urlStr, File file, String downFilePwd) {String responseBody = "";try {MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);FileBody fileBody = new FileBody(file, ContentType.create("multipart/form-data", "utf-8"), file.getName());multipartEntityBuilder.addPart("file", fileBody);Map params = new HashMap();params.put("downloadPassword", downFilePwd);if (params != null && !params.isEmpty()) {Set keyNames = params.keySet();String keyName;StringBody keyValue;for (Iterator iterator = keyNames.iterator(); iterator.hasNext(); multipartEntityBuilder.addPart(keyName, keyValue)) {keyName = (String) iterator.next();keyValue = new StringBody((String) params.get(keyName),ContentType.create("text/plain", "UTF-8"));}}RequestConfig config = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).setConnectionRequestTimeout(30000).build();HttpClientBuilder clientBuilder = HttpClients.custom();clientBuilder.setDefaultRequestConfig(config);KeyStore kstore = KeyStore.getInstance(SSLEntity.caType);kstore.load(new FileInputStream(SSLEntity.filePath),SSLEntity.password.toCharArray());KeyManagerFactory keyFactory = KeyManagerFactory.getInstance("SunX509");keyFactory.init(kstore, SSLEntity.password.toCharArray());TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("TLSv1");sslContext.init(keyFactory.getKeyManagers(), tm, null);SSLConnectionSocketFactory ssl = new SSLConnectionSocketFactory(sslContext,new String[] { "TLSv1" }, null,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);if (ssl != null)clientBuilder.setSSLSocketFactory(ssl);CloseableHttpClient client = clientBuilder.build();CloseableHttpResponse response = null;RequestConfig requestConfig = RequestConfig.copy(config).build();HttpPost httpPost = new HttpPost(urlStr);if (httpPost != null) {if (multipartEntityBuilder != null)httpPost.setEntity(multipartEntityBuilder.build());httpPost.setConfig(requestConfig);response = client.execute(httpPost);} boolean status = response.getStatusLine().getStatusCode() == 200;StringBuilder respText = new StringBuilder();if (status) {HttpEntity entity = response.getEntity();if (entity != null) {BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), "utf-8"));String text;while ((text = bufferedReader.readLine()) != null)respText.append(text);EntityUtils.consume(entity);}}response.close();client.close();responseBody = respText.toString();System.out.println(responseBody);} catch (Exception e) {e.printStackTrace();return Result.toFailedJson(e.getMessage());} return responseBody;}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章