ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

接口上传文件

2021-11-04 18:01:16  阅读:160  来源: 互联网

标签:文件 writeBytes String NEWLINE 接口 httpConn new dos 上传


/**
	 * @param url       请求地址
	 * @param map       请求的参数
	 * @param body_data 上传的文件二进制内容
	 * @param fileName  文件路径
	 * @param charset   字符集
	 * @return
	 */
	public static String fileUpload(String url, Map<String, String> map,
									byte[] body_data, String fileName, String charset) {
		final String NEWLINE = "\r\n";
		final String PREFIX = "--";
		final String BOUNDARY = "#";
		HttpURLConnection httpConn = null;
		BufferedInputStream bis = null;
		DataOutputStream dos = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			URL urlObj = new URL(url);
			httpConn = (HttpURLConnection) urlObj.openConnection();
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setRequestMethod("POST");
			httpConn.setUseCaches(false);
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Accept", "*/*");
			httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
			httpConn.setRequestProperty("Cache-Control", "no-cache");
			httpConn.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);
			httpConn.setRequestProperty(
					"User-Agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)");
			httpConn.connect();

			dos = new DataOutputStream(httpConn.getOutputStream());
			if (map != null && !map.isEmpty()) {
				for (Map.Entry<String, String> entry : map.entrySet()) {
					String key = entry.getKey();
					String value = map.get(key);
					dos.writeBytes(PREFIX + BOUNDARY + NEWLINE);
					dos.writeBytes("Content-Disposition: form-data; "
							+ "name=\"" + key + "\"" + NEWLINE);
					dos.writeBytes(NEWLINE);
					dos.writeBytes(URLEncoder.encode(value.toString(), charset));
					dos.writeBytes(NEWLINE);
				}
			}

			if (body_data != null && body_data.length > 0) {
				dos.writeBytes(PREFIX + BOUNDARY + NEWLINE);
				dos.writeBytes("Content-Disposition: form-data; " + "name=\""
						+ "file" + "\"" + "; filename=\"" + fileName
						+ "\"" + NEWLINE);
				dos.writeBytes(NEWLINE);
				dos.write(body_data);
				dos.writeBytes(NEWLINE);
			}
			dos.writeBytes(PREFIX + BOUNDARY + PREFIX + NEWLINE);
			dos.flush();

			byte[] buffer = new byte[8 * 1024];
			int c = 0;
			if (httpConn.getResponseCode() == 200) {
				bis = new BufferedInputStream(httpConn.getInputStream());
				while ((c = bis.read(buffer)) != -1) {
					baos.write(buffer, 0, c);
					baos.flush();
				}
			}
			return new String(baos.toByteArray(), charset);
		} catch (HttpHostConnectException e) {
			// 找不到服务,但IP通
			throw new RpcException(ClientResCode.RC_HTTP_HTTPHOSTCONNECTEXCEPTION, e.getMessage());
		} catch (UnknownHostException e) {
			// IP错误
			throw new RpcException(ClientResCode.RC_HTTP_UNKNOWNHOSTEXCEPTION, e.getMessage());
		} catch (ConnectTimeoutException e) {
			// IP不通,连接超时
			throw new RpcException(ClientResCode.RC_CONNECT_TIMEOUT, e.getMessage());
		} catch (SocketTimeoutException e) {
			throw new RpcException(ClientResCode.RC_REQUEST_TIMEOUT, e.getMessage());
		} catch (Exception e) {
			throw new RpcException(ClientResCode.RC_OTHER_NETWORK_ERROR, e.getMessage());
		} finally {
			try {
				if (dos != null) {
					dos.close();
				}
				if (bis != null) {
					bis.close();
				}
				if (baos != null) {
					baos.close();
				}
				httpConn.disconnect();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
/**
     * 文件上传接口
     *
     * @param url
     * @param params
     * @param rpcBaseReq
     * @return
     * @throws RpcException
     * @throws Exception
     */
    public String post(String url, String params) throws RpcException, Exception {

        File file = new File(params);// params:pdf所在路径
        byte[] bytes = File2byte(file);
        FileInputStream fileInputStream = new FileInputStream(file);
//        MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
//                ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        String jsonResult = HttpUtil.fileUpload(url, new HashMap<>(),bytes,file.getName(),"utf-8");
//        System.out.println(jsonResult);
        return jsonResult;

    }

    /**
     * 将文件转换成byte数组
     * @param tradeFile
     * @return
     */
    public static byte[] File2byte(File tradeFile){
        byte[] buffer = null;
        try
        {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return buffer;
    }

标签:文件,writeBytes,String,NEWLINE,接口,httpConn,new,dos,上传
来源: https://blog.csdn.net/qq_40572200/article/details/121147775

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有