1. 程式人生 > >HttpClient https上傳檔案與form表單

HttpClient https上傳檔案與form表單

//上傳檔案
public String send(String urlStr, File file, String downFilePwd){
		InputStream responseStream = null;
		String responseBody = "";
		try{
			HttpClient client = new HttpClient();
			client.getParams().setAuthenticationPreemptive(true);
			Protocol authhttps = new Protocol("https",
					new AuthSSLProtocolSocketFactory(new URL((new StringBuilder(
							"file:")).append(SSLEntity.filePath).toString()),
							SSLEntity.password, new URL(
									(new StringBuilder("file:")).append(
											SSLEntity.filePath).toString()),
							SSLEntity.password), 8441);
			Protocol.registerProtocol("https", authhttps);
			client.getParams().setSoTimeout(60000);
			PostMethod postMethod = new PostMethod(urlStr);
			Part[] parts = { new FilePart("file", file),
					new StringPart("downloadPassword", downFilePwd) };
			postMethod.setRequestEntity(new MultipartRequestEntity(parts,
					postMethod.getParams()));
			if (client.executeMethod(postMethod) == 200) {
				responseStream = postMethod.getResponseBodyAsStream();
				if (responseStream != null) {
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					byte[] receiveBuffer = new byte[2048];
					int readBytesSize = responseStream.read(receiveBuffer);
					while (readBytesSize != -1) {
						bos.write(receiveBuffer, 0, readBytesSize);
						readBytesSize = responseStream.read(receiveBuffer);
					}
					responseBody = new String(bos.toByteArray(), "UTF-8");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			return Result.toFailedJson(e.getMessage());
		}finally{
			try {
				responseStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return responseBody;

	}

//上傳form表單

public String download(String urlStr,  String filePath, String uploadTime,
			String batchFileName, String downloadPassword){
		FileOutputStream fout = null;
		InputStream in = null;
		try{
			HttpClient client = new HttpClient();
			client.getParams().setAuthenticationPreemptive(true);
			Protocol authhttps = new Protocol("https",
					new AuthSSLProtocolSocketFactory(new URL((new StringBuilder(
							"file:")).append(SSLEntity.filePath).toString()),
							SSLEntity.password, new URL(
									(new StringBuilder("file:")).append(
											SSLEntity.filePath).toString()),
							SSLEntity.password), 8441);
			Protocol.registerProtocol("https", authhttps);
			client.getParams().setSoTimeout(60000);
			Part[] parts = { new StringPart("uploadTime", uploadTime),
							 new StringPart("batchFileName", batchFileName),
							 new StringPart("downloadPassword", downloadPassword)};
			PostMethod postMethod = new PostMethod(urlStr);
			postMethod.setRequestEntity(new MultipartRequestEntity(parts,
					postMethod.getParams()));
			if (client.executeMethod(postMethod) == 200) {
				Header[] headers = postMethod
						.getResponseHeaders("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");
				}
				try{
					File path = new File(filePath);
					if (!path.exists())
						path.mkdirs();
					batchFileName = (new StringBuilder(String.valueOf(filePath)))
							.append(filePath.endsWith(File.separator) ? ""
									: File.separator)
							.append(strInfo[1].split("\\=")[1]).toString();
					in = postMethod.getResponseBodyAsStream();
					File file = new File(batchFileName);
					fout = new FileOutputStream(file);
					int ret = -1;
					byte tmp[] = new byte[1024];
					while ((ret = in.read(tmp)) != -1)
						fout.write(tmp, 0, ret);
					fout.flush();
				}catch(Exception e){
					e.printStackTrace();
					return Result.toFailedJson(e.getMessage());
				}finally{
					fout.close();
					in.close();
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			return Result.toFailedJson(e.getMessage());
		}
		return Result.toSuccessJson("批量檔案下載成功");
	}

注:該方式jdk6可能會報握手失敗,可切成jdk7或者使用另一篇文章中CloseableHttpClient方式進行通訊。如果有大神知道上述方式怎麼設定https的協議版本(TLSv1),望留言告之,謝謝