自我总结httpclient

13 篇文章 0 订阅
package com.dong.test.httpclient;

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

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

public class TestUpFileHttpClient {

	// file1与file2在同一个文件夹下 filepath是该文件夹指定的路径
	public void SubmitPost(String url, String filename1, String filename2,
			String filepath) {

		HttpClient httpclient = new DefaultHttpClient();

		try {

			HttpPost httppost = new HttpPost(url);

			FileBody bin = new FileBody(new File(filepath + File.separator
					+ filename1));

			FileBody bin2 = new FileBody(new File(filepath + File.separator
					+ filename2));

			StringBody comment = new StringBody("dongruofan");

			MultipartEntity reqEntity = new MultipartEntity();

			reqEntity.addPart("file1", bin);// file1为请求后台的File upload;属性
			reqEntity.addPart("file2", bin2);// file2为请求后台的File upload;属性
			reqEntity.addPart("filename1", comment);// filename1为请求后台的普通参数;属性
			httppost.setEntity(reqEntity);

			HttpResponse response = httpclient.execute(httppost);

			int statusCode = response.getStatusLine().getStatusCode();

			if (statusCode == HttpStatus.SC_OK) {

				System.out.println("服务器正常响应.....");

				HttpEntity resEntity = response.getEntity();

				System.out.println(EntityUtils.toString(resEntity));// httpclient自带的工具类读取返回数据

				System.out.println(resEntity.getContent());

				EntityUtils.consume(resEntity);
			}

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				httpclient.getConnectionManager().shutdown();
			} catch (Exception ignore) {

			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		TestUpFileHttpClient httpPostArgumentTest2 = new TestUpFileHttpClient();

		httpPostArgumentTest2.SubmitPost(
				"http://127.0.0.1:8086/DongWeb/UpFileSmart", "hello.txt",
				"world.txt", "D://test");
	}

}

<pre name="code" class="java">package com.dong.web.main;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UpFile extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public UpFile() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("doGet");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		System.out.println(isMultipart);
		if (isMultipart) {
			String path = request.getSession().getServletContext().getRealPath(
					"/files");
			System.out.println("path::::::::::" + path);
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			try {
				List<FileItem> items = upload.parseRequest(request);
				System.out.println(items.size());
				for (FileItem item : items) {
					if (item.isFormField()) {
						String name1 = item.getFieldName();
						String value = item.getString("UTF-8");
						System.out.println(name1 + "::::" + value);

					} else {
						System.out.println("item.getName()"+item.getName());
						item.write(new File(dir,item.getName()));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else {
			doGet(request, response);
		}

	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}


 



package com.dong.web.main;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;

public class UpFileSmart extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public UpFileSmart() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {

		try {
		
			try {
				SmartUpload smartUpload = new SmartUpload();
				smartUpload.initialize(getServletConfig(), req, response);
				smartUpload.upload("UTF-8");
				Calendar calendar = Calendar.getInstance();
				SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyyMMdd");
				String dir = simpleFormat.format(calendar.getTime());
				Request request = smartUpload.getRequest();
				System.out.println("filename1"+request.getParameter("filename1"));
				Files files = smartUpload.getFiles();
				String picPath = null;
				if (files != null && files.getCount() > 0) {

					java.io.File path = new java.io.File(req.getSession()
							.getServletContext().getRealPath("/filesmart"));

					if (!path.exists())
						path.mkdirs();

					for (int i = 0; i < files.getCount(); i++) {
						File file = files.getFile(i);
						System.out.println("1------>"+file.getFieldName());
						System.out.println("2------>"+file.getFileName());
						System.out.println("3------>"+file.getContentString());
						String getedFileName = "td_"
								+ System.currentTimeMillis() + "_"
								+ file.getFileName();

						if (file.isMissing()) {
							continue;
						}

						picPath = path.getPath() + java.io.File.separator
								+ getedFileName;

						file.saveAs(picPath, File.SAVEAS_AUTO);

					}

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

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

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值