httpclient 二进制流形式上传文件


 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * 二进制流形式上传文
 * 
 */
public class HttpClientTest {
	//客户端上传文件流
	public static void uploadStream(String targetURL, byte[] data) {
		PostMethod filePost = null;
		try {
			filePost = new PostMethod(targetURL);
			// 增加http 请求输入流
			filePost.setRequestEntity(new ByteArrayRequestEntity(data, "text/plain;charset=utf-8"));
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
			int status = client.executeMethod(filePost);
			if (status == HttpStatus.SC_OK) {

				// 响应回文数组
				// ret = filePost.getResponseBody();
				System.out.println(filePost.getResponseBodyAsString());
			} else {
				System.out.println("请求出错,状态:" + status + "," + filePost.getStatusText());
				System.out.println("请求出错,响应:" + filePost.getResponseBodyAsString());
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (filePost != null) {
				filePost.releaseConnection();
			}
		}

	}
	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		String url = "http://127.0.0.1/bp003/rejectionInit";
		File file = new File("d:/bill.ag");
		byte[] bytesArray = new byte[(int) file.length()];
		FileInputStream fis = new FileInputStream(file);
		fis.read(bytesArray); // read file into bytes[]
		fis.close();
		uploadStream(url, bytesArray);
	}
	//服务端接收文件流
	public void download(HttpServletRequest request) {
		FileOutputStream fos = null;
		InputStream in = null;
		try {
			File file = new File("c:/bill.ag");
			in = request.getInputStream();

			fos = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int bytes = 0;
			while ((bytes = in.read(buffer)) != -1) {
				fos.write(buffer, 0, bytes);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			if (fos != null) {
				try {
					fos.flush();
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

 

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 可以使用Spring MVC的ResponseEntity类来下载二进制。例如: ``` @GetMapping("/download") public ResponseEntity<byte[]> downloadFile() throws IOException { byte[] data = // 获取二进制数据 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", "file.txt"); return new ResponseEntity<>(data, headers, HttpStatus.OK); } ``` 其中,byte[]为二进制数据,headers设置文件类型为二进制和文件名,HttpStatus.OK表示请求成功。 ### 回答2: 在Spring框架中,可以使用ResponseEntity来下载二进制。ResponseEntity是一个通用的返回对象,它可以包含HTTP响应的状态码、头部信息和响应体。 首先,我们需要使用HttpClient或者RestTemplate发送HTTP请求获取到包含二进制的响应体。然后,创建一个ResponseEntity对象,将获取到的二进制设置为响应体,并设置Content-Type和Content-Disposition头部信息。 以下是一个使用RestTemplate下载二进制的示例代码: ```java RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); // 设置请求头部信息 headers.set(HttpHeaders.CONTENT_TYPE, "application/octet-stream"); headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=test.txt"); // 发送GET请求 ResponseEntity<byte[]> response = restTemplate.exchange("http://example.com/download", HttpMethod.GET, new HttpEntity<>(headers), byte[].class); // 获取响应体 byte[] binaryData = response.getBody(); // 将二进制保存到本地文件 try (OutputStream outputStream = new FileOutputStream("test.txt")) { outputStream.write(binaryData); outputStream.flush(); System.out.println("文件下载完成"); } catch (IOException e) { e.printStackTrace(); } ``` 以上代码中,我们使用RestTemplate发送一个GET请求,并设置请求头部信息。然后,通过exchange方法获取到响应体的二进制,并保存到本地文件中。 需要注意的是,需要根据实际情况设置Content-Type和Content-Disposition头部信息,以确保下载的文件可以正确显示和保存。 总结起来,使用ResponseEntity下载二进制的步骤包括发送HTTP请求获取响应体,创建ResponseEntity对象,将二进制设置为响应体,并设置头部信息。最后,可以将二进制保存为文件或者进行其他处理。 ### 回答3: ResponseEntity是Spring框架提供的一个用于封装HTTP响应的类,它可以包含响应的状态码、响应头和响应体等信息。可以通过ResponseEntity来下载二进制。 首先,我们需要创建一个请求地址的URL对象。然后,使用Java的URL.openConnection()方法打开一个连接,并将连接强制转换为HttpURLConnection类型,便于设置请求的参数。 设置连接的请求方法为GET,即发送一个GET请求,获取服务器返回的响应。然后,可以通过调用连接的getInputStream()方法获取服务器返回的输入。 接下来,可以创建一个ByteArrayOutputStream对象,用于将输入中的数据写入到内存中的字节数组中。我们可以创建一个缓冲区变量,每次读取一部分数据,然后将数据写入到ByteArrayOutputStream中,直到数据读取完毕。 最后,将ByteArrayOutputStream中的字节数组作为响应体返回给客户端。可以使用ResponseEntity的静态方法ok()来创建一个成功的响应,设置响应的状态码为200,并将字节数组作为响应体返回。 示例代码如下: ```java import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public ResponseEntity<byte[]> downloadBinaryFile() { try { // 请求地址 String fileUrl = "http://example.com/file.bin"; URL url = new URL(fileUrl); // 打开连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // 获取输入 InputStream inputStream = connection.getInputStream(); // 写入字节数组 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } byte[] fileBytes = outputStream.toByteArray(); // 设置响应头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", "file.bin"); // 返回响应实体 return ResponseEntity.ok().headers(headers).body(fileBytes); } catch (Exception e) { e.printStackTrace(); // 返回错误响应 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } ``` 上述代码可以将指定URL的二进制文件下载,并将文件的字节数组作为响应体返回给客户端。同时,还设置了响应头用于指定文件名称和文件类型。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值