java httpclient 上传文件 服务器 servlet 接收

1、新建一个普通的java项目,然后新建个包和类,代码如下:

package com.busymonkey;

import java.io.File;   
import java.io.IOException;   
  
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientUtile {   
	public static void main(String[] args) throws ClientProtocolException,
    IOException {
		args = new String[] { "D:\\test.exe" };
		if (args.length != 1) {
			System.out.println("File path not given");
			System.exit(1);
		}
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httppost = new HttpPost(
					"http://localhost:8080/servlet/Servlet");

			FileBody bin = new FileBody(new File(args[0]));
			StringBody comment = new StringBody("A binary file of some kind",
            ContentType.TEXT_PLAIN);

			HttpEntity reqEntity = MultipartEntityBuilder.create()
					.addPart("bin", bin).addPart("comment", comment).build();

			httppost.setEntity(reqEntity);

			System.out.println("executing request " + 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));
				}
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
	}
}
需要的包(解压后全部拷贝肯定能用)下载地址: 点击打开链接     点击打开链接    点击打开链接



2、首先要有tomcat的运行环境,与eclipse的关联看文章:点击打开链接

然后新建一个动态web项目,并且在项目源文件下新建一个servlet,这样web.xml文件里面应该能自动生成一些映射配置,然后servlet的代码(服务器)如下:

package com.busymonkey;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;

public class Servlet extends HttpServlet {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private static final long FILE_MAX_SIZE = 1024 * 1024 * 200;
    private static final String FILE_SAVE_PATH = "D:\\temp\\";
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("do get");
    }
 
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse resp)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        RequestContext req = new ServletRequestContext(request);
        if (FileUpload.isMultipartContent(req)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            fileUpload.setHeaderEncoding("UTF-8");
            fileUpload.setFileSizeMax(FILE_MAX_SIZE);
            List<FileItem> items = new ArrayList<FileItem>();
            try {
                items = fileUpload.parseRequest(request);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator<FileItem> it = items.iterator();
            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();
                if (fileItem.isFormField()) {
                    System.out.println(fileItem.getFieldName()
                            + " "
                            + fileItem.getName()
                            + " "
                            + new String(fileItem.getString().getBytes(
                                    "ISO-8859-1"), "GBK"));
                } else {
                    System.out.println(fileItem.getFieldName() + " "
                            + fileItem.getName() + " " + fileItem.isInMemory()
                            + " " + fileItem.getContentType() + " "
                            + fileItem.getSize());
                    if (fileItem.getName() != null && fileItem.getSize() != 0) {
                        File fullFile = new File(fileItem.getName());
                        File newFile = new File(FILE_SAVE_PATH
                                + fullFile.getName());
                        try {
                            fileItem.write(newFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println("no file choosen or empty file");
                    }
                }
            }
        }
    }
}

需要用到的包(最好直接放到tomcat部署环境的lib文件夹下,不用每次拷贝)下载地址: 点击打开链接    点击打开链接



3、最后建立好待上传的文件和用于接收的文件夹,路径自己可以在程序里修改,然后先运行服务器端,再运行java 应用程序。


4、注意:如果提示 404 首先检查项目路径下的build目录有没有生成class文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值