利用HttpClient&PostMethod上传文件和请求参数

//HttpClient发起请求
public static String sendUrlFile(String url, String jsonstr) {		
	String result = "";
		try {				
			HttpClient httpclient = new HttpClient();
			PostMethod post = new PostMethod(url);	
			FilePart  filePart = new FilePart("file", new File("/root/桌面/文档/记录.txt"));
			filePart.setCharSet("utf-8");	
			post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
			//Part数组装需要传第的参数和文件等
			Part[] parts = {new StringPart("username",jsonstr , "utf-8"),filePart};
			MultipartRequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
			post.setRequestEntity(entity);
			int code = httpclient.executeMethod(post);
			//拿到响应结果
			result = new String(post.getResponseBody(), "UTF-8");
			//可释放连接
			post.releaseConnection();  
			return result;
		} catch (HttpException h) {
			LOGGER.error("cause HttpException:" + h.getMessage());			
		} catch (Exception i) {
			LOGGER.error("发送请求错误: url cause IOException:" + i.getMessage());
		}
	
	return "";
}

//接收请求服务器端 参数需要和发送端一致

@ResponseBody
@RequestMapping(value = “/login”)
public JsonResult revice(@RequestParam(“file”) MultipartFile file,@RequestParam(“username”)String username) throws IOException{
InputStream in = file.getInputStream();
OutputStream out = new FileOutputStream("/root/桌面/ok.txt");
byte[] bs = new byte[1024];
int len;
while(-1 != (len = (in.read(bs)))){
out.write(bs);
}
JsonResult json = new JsonResult();
System.out.println();
json.setResult(“ok”);
return json;
}

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值