HttpClient 模仿表单上传文件

package compile5;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

/**
* @Description: 模仿表单上传文件  ,将本地文件上传到文件服务器上 
*
 */
public class SendFile {

	public static void main(String[] args) throws ClientProtocolException,
			IOException {
		

        String filepath="D:\\11111.rar";  

        //创建加密上传的参数 
		Date dateNow = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = sdf.format(dateNow);
		StringBuffer key1 = new StringBuffer();
		
		key1.append("123456").append("PRIVATEM").append(time);
		String myCode = MD5.Md5(key1.toString(), 16);
		
   	 	//接收文件的地址
        String urlStr = "http://img.baidu.com/file/receiveFile.jsp";  
        //封装需要上传文件的参数
        Map<String, String> textMap = new HashMap<String, String>();  
        textMap.put("origin", "PRIVATE");  
        textMap.put("time",  time );  
        textMap.put("secure",myCode); 
        
        
		HttpClient httpclient = new DefaultHttpClient();
		//请求处理页面
		HttpPost httppost = new HttpPost( urlStr );
		//创建待处理的文件
		FileBody file = new FileBody(new File(filepath));

		
		//对请求的表单域进行填充
		MultipartEntity reqEntity = new MultipartEntity();
		reqEntity.addPart("file", file);

		if(textMap!=null ){
			Iterator it = textMap.entrySet().iterator();
			while(it.hasNext() ){
				 Map.Entry entry = (Map.Entry)it.next(); 
				String key =  (String) entry.getKey();
				String value = (String)entry.getValue();
				//创建待处理的表单域内容文本
				StringBody bodyValue = new StringBody(value);
				reqEntity.addPart(key , bodyValue);
			}
		}
		
		//设置请求
		httppost.setEntity(reqEntity);
		//执行
		HttpResponse response = httpclient.execute(httppost);

		HttpEntity httpEntity = response.getEntity();
		BufferedReader br = new BufferedReader(new InputStreamReader(httpEntity
				.getContent(), "UTF-8"));
		StringBuffer backData = new StringBuffer();
		String line = null;
		while ((line = br.readLine()) != null) {
			backData.append(line);
		}
		System.out.println(backData.toString()   );
		
 
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 WPF 中使用 HttpClient 上传大文件时,需要对文件进行分块上传,以避免一次性上传大文件导致的内存占用过高的问题。以下是一个示例代码: ```csharp using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; public async Task UploadLargeFile(string filePath, string apiUrl) { try { const int chunkSize = 8192; // 每个分块的大小,可以根据需要进行调整 using (var httpClient = new HttpClient()) { using (var fileStream = File.OpenRead(filePath)) { var totalChunks = (int)Math.Ceiling((double)fileStream.Length / chunkSize); for (int chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) { var buffer = new byte[chunkSize]; var bytesRead = fileStream.Read(buffer, 0, chunkSize); using (var content = new ByteArrayContent(buffer, 0, bytesRead)) { content.Headers.Add("Content-Type", "application/octet-stream"); content.Headers.Add("Content-Disposition", "attachment; filename=\"" + Path.GetFileName(filePath) + "\""); content.Headers.Add("X-Chunk-Index", chunkIndex.ToString()); content.Headers.Add("X-Total-Chunks", totalChunks.ToString()); var response = await httpClient.PostAsync(apiUrl, content); if (!response.IsSuccessStatusCode) { // 处理上传失败的逻辑 return; } } } } } // 文件上传完成 // 处理上传成功的逻辑 } catch (Exception ex) { // 异常处理 } } ``` 在这个示例中,我们将文件分为多个大小为 `chunkSize` 的块,然后逐个块进行上传。每个块的内容会作为字节数组放入 `ByteArrayContent` 中,并通过请求头传递了分块相关的信息(当前块的索引和总块数)。 请注意,在实际使用时,需要根据你的实际需求修改代码,例如调整分块大小、设置其他请求头或请求参数等。另外,还需要根据你的后端 API 的要求来处理上传的分块数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值