使用HttpURLConnection 上传文件

public class HttpClientUtil {
private final static String BOUNDARY = UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");// 边界标识
private final static String PREFIX = "--";// 必须存在
private final static String LINE_END = "\r\n";
private static SSLSocketFactory sslSocketFactory=null;

public static FilezResult<String> uploadFile(String apiurl,Map<String,String>headers,Map<String,String>params,File[] files){

		FilezResult<String> res = new FilezResult<String>();
		HttpURLConnection conn = null;
		InputStream input = null;
		OutputStream os = null;

		try {
			conn = connect(apiurl);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(1000 * 10);
			conn.setReadTimeout(1000 * 10);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Accept", "*/*");
			conn.setRequestProperty("Connection", "keep-alive");
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

			if(!MapUtils.isEmpty(headers)){
				for(Map.Entry<String,String> entry:headers.entrySet()){
					conn.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}

			conn.connect();
 
			os= new DataOutputStream(conn.getOutputStream());

			writeParams(params,os);

			writeFiles(files,os);

			String endTarget=PREFIX+BOUNDARY+PREFIX+LINE_END;

			os.write(endTarget.getBytes());

			os.flush();
			
			int statusCode = conn.getResponseCode();

			if(statusCode == HttpStatus.SC_OK){
				res.setSuccess(true);
				res.setErrcode(statusCode);
				input = conn.getInputStream();
				res.setData(readInputStream(input));
			}else{
				res.setSuccess(false);
				res.setErrcode(statusCode);
				input = conn.getErrorStream();
				res.setErrorMsg(readInputStream(input));
			}
			return res;
		} catch (MalformedURLException e) {
			res.setSuccess(false);
			res.setErrcode(0);
			res.setErrorMsg(e.getMessage());
		} catch (ProtocolException e) {
			res.setSuccess(false);
			res.setErrcode(0);
			res.setErrorMsg(e.getMessage());
		} catch (IOException e) {
			res.setSuccess(false);
			res.setErrcode(0);
			res.setErrorMsg(e.getMessage());
		}finally{
			IOUtils.closeQuietly(input);
			IOUtils.closeQuietly(os);
		}
		return res;
	}
//https 请求设置
 public static HttpURLConnection connect(String url) throws IOException{
		URL uri=new URL(url);
		String protocol=  uri.getProtocol();
		if(HTTP.equals(protocol)&&HTTPS.equals(protocol)){
			throw new MalformedURLException("Only http & https protocols supported");
		}
		
		HttpURLConnection con=(HttpURLConnection) uri.openConnection();
		if (con instanceof HttpsURLConnection) {
			if(sslSocketFactory==null){
				initUnSecureTSL();
			}
			((HttpsURLConnection) con).setSSLSocketFactory(sslSocketFactory);
			((HttpsURLConnection) con).setHostnameVerifier(getInsecureVerifier());
		}
		return con;
	}

private static synchronized void initUnSecureTSL() throws IOException {
		TrustManager trustAllCerts[];
		if (sslSocketFactory != null)
			return;
		trustAllCerts = (new TrustManager[] { new X509TrustManager() {
			public void checkClientTrusted(X509Certificate ax509certificate[], String s) {
			}

			public void checkServerTrusted(X509Certificate ax509certificate[], String s) {
			}

			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		} });
		try {
			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(null, trustAllCerts, new SecureRandom());
			sslSocketFactory = sslContext.getSocketFactory();
		}
		catch (GeneralSecurityException e) {
			throw new IOException("Can't create unsecure trust manager");
		}
	}
    //传请求参数
	private static void writeParams(Map<String, String> params, OutputStream os) throws IOException {
		if(!MapUtils.isEmpty(params)){
			StringBuilder requestParams = new StringBuilder();
			for(Map.Entry<String, String> entry:params.entrySet()){

				requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);//开始标识
				requestParams.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"").append(LINE_END);//分割符
				requestParams.append("Content-Type: text/plain; charset=UTF-8").append(LINE_END);
				requestParams.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
				requestParams.append(LINE_END);
				requestParams.append(entry.getValue());
				requestParams.append(LINE_END);

			}
			//os.write(requestParams.toString().getBytes());//中文乱码
			os.write(requestParams.toString().getBytes("UTF-8"));//解决中文乱码
			os.flush(); 
		}
	}

//传文件
private static void writeFiles(File[] files, OutputStream os) throws IOException {
		for(File file:files){
			InputStream is = null;

			try {
				StringBuilder requestParams = new StringBuilder();
				requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
				requestParams.append("Content-Disposition: form-data; name=\"filedata\";").append("filename=\"").append(file.getName()).append("\"").append(LINE_END);
				requestParams.append("Content-Type: application/octet-stream").append(LINE_END);
				requestParams.append("Content-Transfer-Encoding: 8bit").append(LINE_END);
				requestParams.append(LINE_END);
				os.write(requestParams.toString().getBytes());

				is =  new FileInputStream(file);

				byte [] buff =  new byte[8192];

				int len=0;

				while( (len=is.read(buff))!=-1){
					os.write(buff,0,len);
				}
				os.write(LINE_END.getBytes());
				os.flush();
			} finally{

				IOUtils.closeQuietly(is);

			}

		}

	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值