使用httpclient4上传文件

本文介绍了如何使用HTTPClient4进行文件上传,包括模拟表单上传和以字节流方式上传,提供了核心代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.模拟form表单上传文件,主要是通过httpmime包中MultipartEntity对象,核心代码如下:

File file = new File(filePath);
FileBody fb = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("myFile", fb);

2.以字节流的形式上传文件,主要通过FileEntity,核心代码如下:

File file = new File(filePath);
FileEntity reqEntity = new FileEntity(file);
postMethod.setEntity(reqEntity);


简单的demo程序:

package com.pengkw.client;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
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.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

public class Client {
	
	/**
	 * 读超时时间
	 */
	public static final int READ_TIME_OUT = 3000;
	
	/**
	 * 连接超时时间
	 */
	public static final int CONNECTION_TIME_OUT = 3000;
	
	private HttpClient client;
	
	public Client(){
		init();
	}
	
	public void init(){
		this.client = new DefaultHttpClient();
		this.client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIME_OUT);
		this.client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, READ_TIME_OUT);
	}
	
	public void get(String url){
		HttpGet getMethod = new HttpGet(url);
		try {
			HttpResponse response = client.execute(getMethod);
			HttpEntity entity = response.getEntity();
			System.out.println(response.getStatusLine().getStatusCode());
			System.out.println(EntityUtils.toString(entity));
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			getMethod.releaseConnection();
		}
	}
	
	/**
	 * 普通的post请求
	 * @param url
	 * @param params
	 */
	public void post(String url, Map<String, String> params){
		HttpPost postMethod = new HttpPost(url);
		try {
			
			if(params != null){
				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				Iterator<String> it = params.keySet().iterator();
				while(it.hasNext()){
					String name = it.next();
					nvps.add(new BasicNameValuePair(name, params.get(name)));
				}	
				
				postMethod.setEntity(new UrlEncodedFormEntity(nvps));
			}

			HttpResponse response = client.execute(postMethod);
			HttpEntity entity = response.getEntity();
			System.out.println(response.getStatusLine().getStatusCode());
			System.out.println(EntityUtils.toString(entity));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();
		}
	}
	
	/**
	 * 模拟form表单上传
	 * @param url
	 * @param filePath
	 * @param params
	 */
	public void uploadFileAsForm(String url, String filePath, Map<String, String> params){
		HttpPost postMethod = new HttpPost(url);	
		try {
			File file = new File(filePath);
			FileBody fb = new FileBody(file);
			MultipartEntity reqEntity = new MultipartEntity();
			reqEntity.addPart("myFile", fb);
			if(params != null){
				Iterator<String> it = params.keySet().iterator();
				while(it.hasNext()){
					String name = it.next();
					reqEntity.addPart(name, new StringBody(params.get(name)));
				}
			}
			postMethod.setEntity(reqEntity);
			HttpResponse response = client.execute(postMethod);
			HttpEntity entity = response.getEntity();
			System.out.println(response.getStatusLine().getStatusCode());
			System.out.println(EntityUtils.toString(entity));
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();
		}
	}
	
	/**
	 * 以字节流的形式上传
	 * @param url
	 * @param filePath
	 */
	public void uploadFileAsStream(String url, String filePath){
		HttpPost postMethod = new HttpPost(url);
		File file = new File(filePath);
		FileEntity reqEntity = new FileEntity(file);
		postMethod.setEntity(reqEntity);
		try {
			HttpResponse response = client.execute(postMethod);
			HttpEntity entity = response.getEntity();
			System.out.println(response.getStatusLine().getStatusCode());
			System.out.println(EntityUtils.toString(entity));
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();
		}

	}
	
	/**
	 * close http client
	 */
	public void shutdown(){
		this.client.getConnectionManager().shutdown();
	}
	
	public static void main(String[] args) {
		Client client = new Client();
		client.get("http://www.baidu.com");
		client.shutdown();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值