HttpClient 向tomcat服务器发送文件

2 篇文章 0 订阅
1 篇文章 0 订阅

HttpClient 向tomcat服务器发送文件

最近在做一个小的安卓app,从来没有用过httpclient 第一次用他作为连接服务器的枢纽,上传的例子结果发现网上大多数都是通过 HttpURLConnection 文件发送的实例,于是自己学习探索一下另一条路,参考了很多博客和api ,实现了简单的上传功能,于是跟大家分享一下:

客户端:

  • HttpPost & HttpEntity
  • HttpClient & HttpResponse
  • MultipartEntity
  • ContentBody & StringBody

jar包:

httpcomponents-client-4.2.5-bin
客户端需要的jar包


代码

package upload;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

public class UploadTest {

    public static void main(String[] args) throws UnsupportedEncodingException {
        MultipartEntity entity =new MultipartEntity();
        ContentBody fileBody = new FileBody(new File("D:\\test.png"));// 初始化文件
        StringBody  comment = new StringBody(new String("啦啦啦啦")); // 初始化非文件的文字

        entity.addPart("file", fileBody);
        entity.addPart("msg", comment);

        HttpPost httpPost= new HttpPost();
        HttpClient httpClient=null;
        HttpResponse response =null;
        HttpEntity result = null;


        httpPost.setEntity(entity); // 封装到httpPost 准备发送数据

        httpClient= new DefaultHttpClient(); // 实例化一个 默认的httpClient

        try {
            response=httpClient.execute(httpPost);// 发送数据并返回一个httpResponse对象
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int statusCode= response.getStatusLine().getStatusCode();
        if(statusCode==HttpStatus.SC_OK) // 即 200 时  通讯成功
        {
            System.out.println("上传成功");
            result= response.getEntity();// 拿到服务器返回的实体
        }else 
            System.out.println("上传失败");

    }

}

tomcat服务器: UploadServlet

用到的类和方法
- DiskFileItemFactory
- ServletFileUpload
- Iterator
- FileItem

需要的jar包:

commons-io-2.2
commons-fileupload-1.3.1-bin
这里写图片描述
这里写图片描述

为了简便这里只写doPost方法
public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        HashMap <String,Object> map= new HashMap<String, Object>(); // 拿到其他信息
        List<FileItem> items =null;
        File directory=null;

        DiskFileItemFactory factory= new DiskFileItemFactory();
        ServletFileUpload upload= new ServletFileUpload(factory);
        try {
             items =upload.parseRequest(request);
        } catch (FileUploadException e) {
            System.out.println("解析出错");
            e.printStackTrace();
        }
        Iterator<FileItem> itemItr= items.iterator();  
        try{

        while(itemItr.hasNext())
        {
             FileItem fItem= itemItr.next();
             String fName="";
             Object fValue=null;
             if(fItem.isFormField()) // 普通文本
             {
                 fName=fItem.getFieldName();
                 fValue=fItem.getString("utf-8");
                 map.put(fName, fValue);
             }else // 文件
             {
                  fName = fItem.getFieldName();  
                  fValue = fItem.getInputStream();  
                  map.put(fName, fValue);  
                  String name = fItem.getName();  
                  if(name != null && !("".equals(name))) {  
                      name = name.substring(name.lastIndexOf(File.separator) + 1);  
                      long timestamp_Str= System.currentTimeMillis();
                      directory = new File("d://upload");    
                      directory.mkdirs();  
                      String filePath = ("d://testBBBB")+"/"+ timestamp_Str+ name;  
                      map.put(fName + "FilePath", filePath);  
                      System.out.println();  
                      InputStream is = fItem.getInputStream();  
                      FileOutputStream fos = new FileOutputStream(filePath);  
                      byte[] buffer = new byte[1024];  
                      while (is.read(buffer) > 0) {  
                          fos.write(buffer, 0, buffer.length);  
                      }  
                      fos.flush();  
                      fos.close();  
                      map.put(fName + "FileName", name);  
                  }  
             }
        }
      } catch (Exception e) {  
          System.out.println("读取http请求属性值出错!");  
        e.printStackTrace();  
      }  

      // 数据处理  
      try {  
          out = response.getWriter();  
          out.print("{success:true, msg:'接收成功'}");  
          out.close();  
      } catch (IOException e) {  
          e.printStackTrace();  
      }  

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值