HttpClient和RestTemplate通过post上传文件和普通参数

 PostMethod

PostMethod filePost = new PostMethod(Const.URL);
try {

	// FilePart:用来上传文件的类
	File file = new File("/mnt/sdcard/111.png");
	FilePart fp = new FilePart("image", file); // Part:类专门用来上传文件,其子类 ,FilePart:用来上传文件的类 StringPart:普通的文本参数
	System.out.println("---" + fp);

	fp.setContentType(getMimeType("/mnt/sdcard/111.png"));

	// StringPart:普通的文本参数
	StringPart uname = new StringPart("email", "279717004@qq.com");

	Part[] parts = { uname, fp };

	// 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
	MultipartRequestEntity mre = new MultipartRequestEntity(parts, filePost.getParams());

	filePost.setRequestEntity(mre);

	HttpClient client = new HttpClient();
	client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// 设置连接时间
	int status = client.executeMethod(filePost);
	System.out.println(status + "--------------");
	if (status != HttpStatus.SC_OK) {
		System.out.println(status + "--------------fail----");
	} else if (status == HttpStatus.SC_OK) {
		String str = "";
		str = filePost.getResponseBodyAsString();
		System.out.println(filePost.getResponseBodyAsString() + "---------服务器返回值---------");
	}

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

 RestTemplate:

String filepath = "E:\\asd.xlsx";
String url = HTTPS_PREFIX + "127.0.0.1" + ":" + "18080" + "/hello";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

File file = new File(filepath);
FileSystemResource resource = new FileSystemResource(file);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file", resource);
param.add("type", "0");

HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(param, headers);
ResponseEntity<JSONObject> response = null;

try {
    response = infoRestTemplate.exchange(url, HttpMethod.POST, entity, JSONObject.class);
    JSONObject responseBody = response.getBody();
    Integer statusCode = (Integer) responseBody.get("code");
    if (statusCode == 0) {
        logger.info("{}", responseBody);
    } catch (Exception e) {
        logger.error("", e);
    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值