HTTPS模拟表单发送参数和图片

项目中需要上传一系统的参数和车辆出入场图片。

    /**
     * @param serverUrl 请求的URL
     * @param paramMap  要发送的参数
     * @param filePath  图片路径
     * @return
     */
	public static String sendFile(String serverUrl, Map<String, Object> paramMap, String filePath) {
		String strResponse = null;
		String boundary = "----------------------7dc2eeba03c6";
		try {
			URL url = new URL(serverUrl);
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			logger.info("=============== 开始设置SSL");
			setSSLSocketFactory(connection, false, false, null, null);
			logger.info("=============== SSL设置完成");
			
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			
			//传输内容
			StringBuffer contentBody = new StringBuffer("--" + boundary);
			
			OutputStream out = connection.getOutputStream();
			
			//1.处理文字参数
			if(paramMap != null){
				for(String key : paramMap.keySet()){
					contentBody.append("\r\n")
					.append("Content-disposition: form-data;name=\"")
					.append(key + "\"")
					.append("\r\n")
					.append("\r\n")
					.append(paramMap.get(key))
					.append("\r\n")
					.append("--")
					.append(boundary);
				}
			}
			
			logger.info("boundaryMessage1:" + contentBody.toString());
			out.write(contentBody.toString().getBytes("utf-8"));
			
			//2处理文件上传
			StringBuffer fileContentBody = new StringBuffer("\r\n")
			.append("Content-disposition:form-data; name=\"image\"; filename=\"ARTC0" + System.currentTimeMillis() + ".jpg\"\r\n")
			.append("Content-Type:image/jpg\r\nContent-Transfer-Encoding: binary\r\n\r\n");
			
			logger.info("boundaryMessage2:" + fileContentBody.toString());
			out.write(fileContentBody.toString().getBytes("utf-8"));
			
			//开始真正向服务器写文件
			File file = new File(filePath);
			if(!file.exists() || !file.isFile()){
				throw new IOException("对应文件不存在");
			}
			DataInputStream in = new DataInputStream(new FileInputStream(file));
			int bytes = 0;
			byte[] bufferOut = new byte[1024];
			while ((bytes = in.read(bufferOut)) != -1) {
				out.write(bufferOut, 0, bytes);
			}
			in.close();
			
			//3.结尾部分
			byte[] foot = ("\r\n--" + boundary + "--\r\n").getBytes("UTF-8");
			out.write(foot);
			out.flush();
			out.close();
			
			StringBuffer buffer = new StringBuffer();
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				String line = null;
				while ((line = reader.readLine()) != null) {
					buffer.append(line);
				}
				if(null == strResponse){
					strResponse = buffer.toString();
				}
			} catch (Exception e) {
				logger.error("====================发送POST请求出现异常" + e.getMessage(),e);
				throw new IOException("数据读取异常");
			} finally {
				if(reader != null){
					reader.close();
				}
			}
			logger.info("=====================调用图片上传接口返回内容为:" + strResponse);
			return strResponse;
		} catch (Exception e) {
			logger.error("=====================调用图片上传接口出错:" + e.getMessage());
			e.printStackTrace();
		}
		return strResponse;
	  }


注意图片的name和filename要设置,各个换行要严格控制。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值