接口都以文件形式请求或返回

请求参数

body参数及说明

参数名 示例值 参数类型 是否必填 参数描述
filename E:\tar\test1.tar File
-
name test1
        String resultInfo = "";
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            CloseableHttpResponse httpResponse = null;
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
            HttpPost httpPost = new HttpPost(pathUrl);
            httpPost.setConfig(requestConfig);
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            File file = new File(fileName);
            multipartEntityBuilder.addBinaryBody("filename",file);
            multipartEntityBuilder.addTextBody("name", formName);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpPost.setEntity(httpEntity);
            httpResponse = httpClient.execute(httpPost);
            HttpEntity responseEntity = httpResponse.getEntity();
            
            //返回的文件存储
            /*File filett = new File("e:/test2.tar");
            InputStream inputStream = responseEntity.getContent();
            byte[] bytes = IOUtils.toByteArray(inputStream);
            FileUtils.writeByteArrayToFile(filett, bytes);*/

          int statusCode= httpResponse.getStatusLine().getStatusCode();
            logger.info("statusCode="+statusCode);  
            if(statusCode == 200){
                BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
                StringBuffer buffer = new StringBuffer();
                String str = "";
                while((str = reader.readLine()) != null) {
                    buffer.append(str);
                }
                resultInfo = buffer.toString();
            }
            httpClient.close();
            if(httpResponse!=null){
                httpResponse.close();
            }
		} catch (Exception e) {
			// TODO: handle exception
		} 
        return resultInfo ;

 返回文件

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Disposition: attachment;filename=test.tar
Content-Type: application/x-tar;charset=UTF-8
Transfer-Encoding: chunked
Content-Length: 1000
Date: Sat, 14 May 2022 02:22:56 GMT
    @ResponseBody
	public synchronized void ebdfile() {
		try {
			
			File responseFile = new File("/home/test/test.tar");			
			response.setHeader("Content-Disposition", "attachment;filename=test.tar");
			response.setHeader("Content-Type", "application/x-tar");
			response.setHeader("Content-Length", ""+responseFile.length());
			FileCopyUtils.copy(new FileInputStream(responseFile), response.getOutputStream());
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

第二种:

public static String httpPostUtil(String pathUrl, String formName, String fileName) {
		String baseResult = null;
		URL postUrl = null;
		String BOUNDARY = UuidUtil.get32UUID();

		HttpURLConnection connection = null;
		try {
			final String newLine = "\r\n";
			final String boundaryPrefix = "--";

			postUrl = new URL(pathUrl);
			connection = (HttpURLConnection) postUrl.openConnection();
			connection.setRequestMethod("POST");

			connection.setReadTimeout(15 * 1000); // 缓存的最长时间
			connection.setDoInput(true);// 允许输入
			connection.setDoOutput(true);// 允许输出
			connection.setUseCaches(false); 

			connection.setRequestProperty("connection", "Keep-Alive");// 设置请求头参数
			connection.setRequestProperty("Charsert", "UTF-8");
			connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());

			File file = new File(fileName);
			StringBuilder sb = new StringBuilder();
			sb.append(boundaryPrefix);
			sb.append(BOUNDARY);
			sb.append(newLine);
			sb.append(
					"Content-Disposition: form-data;name=\"" + formName + "\";filename=\"" + file.getName() + "\"" + newLine);
			sb.append("Content-Type:application/x-tar");
			sb.append(newLine);
			sb.append(newLine);

			out.write(sb.toString().getBytes());// 将参数头的数据写入到输出流中

			DataInputStream in = new DataInputStream(new FileInputStream(file));// 数据输入流,用于读取文件数据
//			InputStream in = new FileInputStream(file);
			byte[] bufferOut = new byte[1024];
			int bytes = 0;

			while ((bytes = in.read(bufferOut)) != -1) {// 每次读1KB数据,并且将文件数据写入到输出流中
				out.write(bufferOut, 0, bytes);
			}

			out.write(newLine.getBytes());
//			out.flush();
//			out.close();
			in.close();

			byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine).getBytes();

			out.write(end_data);
			out.flush();
			out.close();
			int res = connection.getResponseCode();
			logger.info("getResponseCod:"+res);
//			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
//			String line = null;
//			StringBuffer strs = new StringBuffer("");
//			while ((line = reader.readLine()) != null) {
//				strs.append(line);
//			}
//			baseResult = strs.toString();

			connection.disconnect();
		} catch (Exception e) {
			// TODO: handle exception
			if (connection != null) {
				connection.disconnect();
			}
		}
		logger.info("baseResult="+baseResult);
		return baseResult;
	}

name定义的和接收的值保持一致

猜你喜欢

转载自blog.csdn.net/wyyother1/article/details/124767376