httpclient文件上传、下载

1.文件上传
// 把文件转换成流对象FileBody
File file =newFile(filePath);
FileBody bin =newFileBody(file); 
StringBody uploadFileName =newStringBody("把我修改成文件名称", ContentType.create("text/plain", Consts.UTF_8));
//以浏览器兼容模式运行,防止文件名乱码
HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
    // 相当于
    .addPart("uploadFile", bin)//uploadFile对应服务端类的同名属性
    // 相当于
    .addPart("uploadFileName", uploadFileName)//uploadFileName对应服务端类的同名属性
    .setCharset(CharsetUtils.get("UTF-8")).build();
httpPost.setEntity(reqEntity);


2.文件下载
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();

你可能感兴趣的:(httpclient文件上传、下载)