HttpClient4.5.2由Client客户端上传File文件流至Server服务端

应用场景:

java代码部分做文件资源同步。比如:应用系统将上传的文件备份或同步至文件服务器中。

代码位置

位于java client相关代码部分,将文件流通过httpClient工具发送网络请求到服务器上。

关键代码

将java.io.File对象添加到HttpEntity(org.apache.http.HttpEntity)对象中:

MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
mEntityBuilder.addBinaryBody("file", file);
httppost.setEntity(mEntityBuilder.build());

Client完整代码

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class FileClient {
	/**
	 * 将文件提交至文件服务器
	 * @param file 文件对象
	 * @return FileStatus 上传结果
	 */
	public static String postFile(File file) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String result = null;
		try {
			HttpPost httpPost = new HttpPost(ServerURL.URL_FILE_POST);
			MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
			mEntityBuilder.addBinaryBody("file", file);
			httpPost.setEntity(mEntityBuilder.build());
			response = httpclient.execute(httpPost);

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity resEntity = response.getEntity();
				result =EntityUtils.toString(resEntity);
				// 消耗掉response
				EntityUtils.consume(resEntity);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			HttpClientUtils.closeQuietly(httpclient);
			HttpClientUtils.closeQuietly(response);
		}
		return result;
	}
}

Server代码

	/**
	 * 上传文件
	 * @param fileRequest
	 */
	@RequestMapping("/postFile")
	public void postFile(HttpServletRequest request, HttpServletResponse response) {
		String result = "error";
		Map<String, Object> map = new HashMap<String, Object>();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()
				.getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 取得上传文件
				MultipartFile multipartFile = multiRequest.getFile(iter.next());
				if (multipartFile != null) {
					// 取得当前上传文件的文件名称
					String fileName = multipartFile.getOriginalFilename();
					if (fileName.trim() != null && fileName.trim().length() > 0) {
						CommonsMultipartFile cf = (CommonsMultipartFile) multipartFile;
						DiskFileItem fi = (DiskFileItem) cf.getFileItem();
						File tempFile = fi.getStoreLocation();
						// 拿到文件,存储
						...
						result = "success";
					}
				}
			}
		}
	}
	map.put("result", result);
	this.renderJson(response, map);
}

其中,renderJson的代码见:

/**
 * 输出文本内容到页面上
 * @param text 文本内容
 * @param contentType 返回类型
 */
private void render(HttpServletResponse response, String text, String contentType) {
	if (response != null) {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType(contentType);
		PrintWriter pWriter = null;
		try {
			pWriter = response.getWriter();
			pWriter.write(text);
			pWriter.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pWriter != null) {
				pWriter.close();
			}
		}
	}
}

/**
 * 输出普通文本到页面
 * @param text 普通文本
 */
protected void renderText(HttpServletResponse response, String text) {
	this.render(response, text, "text/plain;charset=UTF-8");
}

/**
 * 输出Html格式的文本到页面
 * @param text Html文本内容
 */
protected void renderHtml(HttpServletResponse response, String html) {
	this.render(response, html, "text/html;charset=UTF-8");
}

/**
 * 输出Json格式的文本到页面
 * @param json Json文本内容
 */
protected void renderJson(HttpServletResponse response, String json) {
	this.render(response, json, "text/json;charset=UTF-8");
}

/**
 * 输出Json格式的文本到页面
 * @param obj 待转换对象
 */
protected void renderJson(HttpServletResponse response, Object obj) {
	Gson gson = new Gson();
	String json = gson.toJson(obj);
	this.renderJson(response, json);
}

/**
 * 输出XML格式的文本到页面
 * @param xml XML文本内容
 */
protected void renderXML(HttpServletResponse response, String xml) {
	this.render(response, xml, "text/xml;charset=UTF-8");
}

/**
 * 输出结果“success”到页面
 */
protected void renderSuccess(HttpServletResponse response) {
	this.renderText(response, SUCCESS);
}

/**
 * 输出结果“error”到页面
 */
protected void renderError(HttpServletResponse response) {
	this.renderText(response, ERROR);
}

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
### 回答1: 在Java后端,使用HttpClient库进行POST请求提交文件流,包括以下步骤: 1. 导入HttpClient库的依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` 2. 创建HttpClient对象: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 3. 创建HttpPost对象,并设置URL和请求体: ```java HttpPost httpPost = new HttpPost("http://example.com/upload"); File file = new File("path/to/file"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("file", new FileBody(file)); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); ``` 4. 执行POST请求并获取响应: ```java CloseableHttpResponse response = httpClient.execute(httpPost); ``` 在服务端接收文件流的代码如下: 1. 创建Spring Boot Controller并监听指定URL: ```java @RestController public class FileUploadController { @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { // 处理文件流 // ... return "File uploaded successfully."; } } ``` 2. 接收到请求时,Spring框架会自动将文件流绑定到`MultipartFile`对象,并调用`handleFileUpload`方法进行处理。 以上就是使用HttpClient库进行Java后端HTTP POST请求提交文件流以及服务端接收文件流的简单示例。 ### 回答2: 在Java后端中使用HttpClient进行post请求提交文件流的步骤如下: 1. 引入相关的依赖,如Apache HttpClient: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` 2. 创建HttpClient对象: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 3. 创建HttpPost请求对象: ```java HttpPost httpPost = new HttpPost(url); ``` 其中,`url`为服务端接收文件流的接口地址。 4. 创建File实例或通过其他方式获取要上传文件流: ```java File file = new File("path/to/file"); FileBody fileBody = new FileBody(file); ``` 5. 创建HttpEntity,并将文件对象添加到其中: ```java MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("file", fileBody); HttpEntity httpEntity = builder.build(); ``` 6. 设置请求的Entity为刚创建的HttpEntity: ```java httpPost.setEntity(httpEntity); ``` 7. 发送post请求并获取响应: ```java CloseableHttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity responseEntity = httpResponse.getEntity(); ``` 以上是使用HttpClientJava后端进行post请求提交文件流的基本步骤。 在服务端接收文件流的代码示例如下(以Spring Boot为例): 1. 创建用于接收文件流的接口: ```java @PostMapping("/upload") public void uploadFile(MultipartFile file) { // 处理文件流的业务逻辑 } ``` 2. 在接口中使用MultipartFile对象接收文件流,Spring Boot会自动将上传文件流封装成MultipartFile对象。 3. 可以在接口中进行一些与文件相关的处理,如保存文件、读取文件内容等。 以上就是使用Java后端的HttpClinet进行文件流提交以及在服务端接收文件流的简单介绍。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值