使用原生Http向接口传输File文件

Java中使用Http接口传输文件

工具类静态常量

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

主方法

/**
 *  POST Multipart Request
 *  @Description:
 *  @param requestUrl 请求url
 *  @param requestText 请求参数(字符串键值对map)
 *  @param requestFile 请求上传的文件列表(File)
 *  @return
 *  @throws Exception
 */
public static String sendRequest(String requestUrl, Map<String, String> requestText, Map<String, File> requestFile) throws Exception{
	HttpURLConnection conn = null;
	InputStream input = null;
	OutputStream os = null;
	BufferedReader br = null;
	StringBuffer buffer = null;
	try {
		URL url = new URL(requestUrl);
		conn = (HttpURLConnection) url.openConnection();

		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		conn.setConnectTimeout(1000 * 10);
		conn.setReadTimeout(1000 * 30);
		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);
		conn.connect();

		// 往服务器端写内容 也就是发起http请求需要带的参数
		os = new DataOutputStream(conn.getOutputStream());
		// 请求参数部分
		writeParams(requestText, os);
		// 请求上传文件部分
		writeFile(requestFile, os);
		// 请求结束标志
		String endTarget = PREFIX + BOUNDARY + PREFIX + LINE_END;
		os.write(endTarget.getBytes());
		os.flush();

		if(conn.getResponseCode()==200){
			input = conn.getInputStream();
		}else{
			input = conn.getErrorStream();
		}

		br = new BufferedReader(new InputStreamReader( input, "UTF-8"));
		buffer = new StringBuffer();
		String line = null;
		while ((line = br.readLine()) != null) {
			buffer.append(line);
		}

	} catch (Exception e) {
		log.error("发送请求错误"+e.getMessage());
		throw new Exception(e);
	} finally {
		try {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}

			if (os != null) {
				os.close();
				os = null;
			}

			if (br != null) {
				br.close();
				br = null;
			}
		} catch (IOException ex) {
			throw new Exception(ex);
		}
	}
	return buffer.toString();
}

其他方法

/**
	 * 对post参数进行编码处理并写入数据流中
	 * @throws Exception
	 * @throws IOException
	 *
	 * */
private static void writeParams(Map<String, String> requestText,
								OutputStream os) throws Exception {
	try{
		StringBuilder requestParams = new StringBuilder();
		Set<Map.Entry<String, String>> set = requestText.entrySet();
		Iterator<Entry<String, String>> it = set.iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = it.next();
			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.flush();
	}catch(Exception e){
		throw new Exception(e);
	}
}

/**
 * 对post上传的文件进行编码处理并写入数据流中
 *
 * @throws IOException
 *
 * */
private static void writeFile(Map<String, File> requestFile,
							  OutputStream os) throws Exception {
	InputStream is = null;
	try{
		//String msg = "请求上传文件部分:\n";
		if (requestFile == null || requestFile.isEmpty()) {
			return;
			//msg += "空";
		} else {
			StringBuilder requestParams = new StringBuilder();
			Set<Map.Entry<String, File>> set = requestFile.entrySet();
			Iterator<Entry<String, File>> it = set.iterator();
			while (it.hasNext()) {
				Entry<String, File> entry = it.next();
				requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
				requestParams.append("Content-Disposition: form-data; name=\"")
						.append(entry.getKey()).append("\"; filename=\"")
						.append(entry.getValue().getName()).append("\"")
						.append(LINE_END);
				requestParams.append("Content-Type:")
						.append(getContentType(entry.getValue()))
						.append(LINE_END);
				requestParams.append("Content-Transfer-Encoding: 8bit").append(
						LINE_END);
				requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容

				os.write(requestParams.toString().getBytes());

				is = new FileInputStream(entry.getValue());

				byte[] buffer = new byte[1024*1024];
				int len = 0;
				while ((len = is.read(buffer)) != -1) {
					os.write(buffer, 0, len);
				}
				os.write(LINE_END.getBytes());
				os.flush();
				//msg += requestParams.toString();
			}
		}
		//System.out.println(msg);
	}catch(Exception e){
		throw new Exception(e);
	}finally{
		try{
			if(is!=null){
				is.close();
			}
		}catch(Exception e){
			throw new Exception(e);
		}
	}
}

/**
 * ContentType
 *
 * @Description:
 * @param file
 * @return
 * @throws IOException
 */
public static String getContentType(File file) throws Exception{
	String streamContentType = "application/octet-stream";
	String fileNameTmp = file.getName().toLowerCase(Locale.ENGLISH);
	if (fileNameTmp.endsWith("csv")) {
		return "text/csv";
	}
	if (fileNameTmp.endsWith("txt")) {
		return "text/plain";
	}
	if (fileNameTmp.endsWith("gif")) {
		return "image/gif";
	}
	if (fileNameTmp.endsWith("jpg")|| fileNameTmp.endsWith("jpg") || fileNameTmp.endsWith("jpeg") || fileNameTmp.endsWith("jpe")) {
		return "image/jpeg";
	}
	if (fileNameTmp.endsWith("zip")) {
		return "application/zip";
	}
	if (fileNameTmp.endsWith("rar")) {
		return "application/rar";
	}
	if (fileNameTmp.endsWith("doc")) {
		return "application/msword";
	}
	if (fileNameTmp.endsWith("ppt")) {
		return "application/vnd.ms-powerpoint";
	}
	if (fileNameTmp.endsWith("xls")) {
		return "application/vnd.ms-excel";
	}
	if (fileNameTmp.endsWith("html") || fileNameTmp.endsWith("htm")) {
		return "text/html";
	}
	if (fileNameTmp.endsWith("tif") || fileNameTmp.endsWith("tiff")) {
		return "image/tiff";
	}
	if (fileNameTmp.endsWith("pdf")) {
		return "application/pdf";
	}
	return streamContentType;
}

调用示例

/**
    *
    * @param uploadFilePath 上传FTP保存路径  例:  /eshopOrder/mtqs
    * @param uploadFileName 上传FTP保存的文件名   例: mtqs_20210726.csv
    * @param uploadFile 要上传的文件
    * @return
    */
   public String sendFileToGDDX(String uploadFilePath, String uploadFileName, File uploadFile){
       String result = "";

       String uploadUrl = "http://"+ RoundRobin.getBankbakServer() +"/queryLLWX/QueryNate.shtml?action=sendFileToSZFTP&type=%s&timestamp=%s&sign=%s";
       try {
           //签名验证
           String timestamp = System.currentTimeMillis()+"";
           String type = "sendFileToGDDX";
           Map<String, String> check = new HashMap<>();
           check.put("type", type);
           check.put("timestamp", timestamp);
           String sign = AESUtil.encrypt(AESUtil.getSortParam(check));
           uploadUrl = String.format(uploadUrl,type, timestamp, sign);
           //封装参数
           Map<String, String> requestMap = new HashMap<>();
           requestMap.put("uploadFileName", uploadFileName);
           requestMap.put("uploadFilePath", "/WsyytWeChat"+uploadFilePath);
           Map<String, File> FileMap = new HashMap<>();
           FileMap.put("uploadFile", uploadFile);

           result = MHttpsUtil.sendRequest(uploadUrl, requestMap, FileMap);
       }catch (Exception e){
           result = "post File Error:"+e.getMessage();
       }
       return result;
   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值