java 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 UploadTest {
	
	// file1与file2在同一个文件夹下 filepath是该文件夹指定的路径
	public void SubmitPost(String url, String filename1, String filepath) {

		HttpClient httpclient = new DefaultHttpClient();

		try {
			HttpPost httppost = new HttpPost(url);
			FileBody bin = new FileBody(new File(filepath + File.separator + filename1));
			StringBody comment = new StringBody("aaa");
			MultipartEntity reqEntity = new MultipartEntity();
			reqEntity.addPart("file", bin);// file1为请求后台的File upload;属性
			reqEntity.addPart("name", comment);// filename1为请求后台的普通参数;属性
			httppost.setEntity(reqEntity);
                        // 后台以ajax方式处理
			httppost.setHeader("X-Requested-With", "XMLHttpRequest");
			HttpResponse response = httpclient.execute(httppost);

			int statusCode = response.getStatusLine().getStatusCode();
			System.out.println("statusCode: " + statusCode);
			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) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				httpclient.getConnectionManager().shutdown();
			} catch (Exception ignore) {

			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		UploadTest httpPostArgumentTest2 = new UploadTest();
		httpPostArgumentTest2.SubmitPost("http://localhost:8080/maintenance/repair-mans/importing/upload", "a.xls", "E:");
	}

}



<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient-cache</artifactId>
			<version>4.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.1.2</version>
		</dependency>

猜你喜欢

转载自onepiece021.iteye.com/blog/2306179
今日推荐