[转]httpclient 上传文件下载文件

Posted 897807300

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[转]httpclient 上传文件下载文件相关的知识,希望对你有一定的参考价值。

用httpclient4.3 post方式推送文件到服务端  
准备:httpclient-4.3.3.jar;httpcore-4.3.2.jar;httpmime-4.3.3.jar
/**
* 上传文件 * @throws ParseException * @throws IOException */ publicstaticvoidpostFile()throwsParseException, IOException{ CloseableHttpClient httpClient = HttpClients.createDefault(); try{ // 要上传的文件的路径 String filePath =newString("F:/pic/001.jpg"); // 把一个普通参数和文件上传给下面这个地址 是一个servlet HttpPost httpPost =newHttpPost( "http://localhost:8080/xxx/xxx.action"); // 把文件转换成流对象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对应服务端类的同名属性<File类型> .addPart("uploadFileName", uploadFileName)//uploadFileName对应服务端类的同名属性<String类型> .setCharset(CharsetUtils.get("UTF-8")).build(); httpPost.setEntity(reqEntity); System.out.println("发起请求的页面地址 "+ httpPost.getRequestLine()); // 发起请求 并返回请求的响应 CloseableHttpResponse response = httpClient.execute(httpPost); try{ System.out.println("----------------------------------------"); // 打印响应状态 System.out.println(response.getStatusLine()); // 获取响应对象 HttpEntity resEntity = response.getEntity(); if(resEntity !=null) { // 打印响应长度 System.out.println("Response content length: " + resEntity.getContentLength()); // 打印响应内容 System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8"))); } // 销毁 EntityUtils.consume(resEntity); }finally{ response.close(); } }finally{ httpClient.close(); } } /** * 下载文件 * @param url * @param destFileName xxx.jpg/xxx.png/xxx.txt * @throws ClientProtocolException * @throws IOException */ publicstaticvoidgetFile(String url, String destFileName) throwsClientProtocolException, IOException { // 生成一个httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget =newHttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); File file =newFile(destFileName); try{ FileOutputStream fout =newFileOutputStream(file); intl = -1; byte[] tmp =newbyte[1024]; while((l = in.read(tmp)) != -1) { fout.write(tmp,0, l); // 注意这里如果用OutputStream.write(buff)的话,图片会失真,大家可以试试 } fout.flush(); fout.close(); }finally{ // 关闭低层流。 in.close(); } httpclient.close(); }

 

以上是关于[转]httpclient 上传文件下载文件的主要内容,如果未能解决你的问题,请参考以下文章

Xamarin.Forms 使用HttpClient上传文件

android的自带的httpClient 怎么上传文件

HttpClient 通过 PostAsync 上传文件的奇怪行为

Android开发之httpclient文件上传实现

httpclient 实现文件上传中转

Titanium HTTPCLIENT 无法上传文件