httpclient 二进制流形式上传文件


 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * 二进制流形式上传文
 * 
 */
public class HttpClientTest {
	//客户端上传文件流
	public static void uploadStream(String targetURL, byte[] data) {
		PostMethod filePost = null;
		try {
			filePost = new PostMethod(targetURL);
			// 增加http 请求输入流
			filePost.setRequestEntity(new ByteArrayRequestEntity(data, "text/plain;charset=utf-8"));
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
			int status = client.executeMethod(filePost);
			if (status == HttpStatus.SC_OK) {

				// 响应回文数组
				// ret = filePost.getResponseBody();
				System.out.println(filePost.getResponseBodyAsString());
			} else {
				System.out.println("请求出错,状态:" + status + "," + filePost.getStatusText());
				System.out.println("请求出错,响应:" + filePost.getResponseBodyAsString());
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (filePost != null) {
				filePost.releaseConnection();
			}
		}

	}
	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		String url = "http://127.0.0.1/bp003/rejectionInit";
		File file = new File("d:/bill.ag");
		byte[] bytesArray = new byte[(int) file.length()];
		FileInputStream fis = new FileInputStream(file);
		fis.read(bytesArray); // read file into bytes[]
		fis.close();
		uploadStream(url, bytesArray);
	}
	//服务端接收文件流
	public void download(HttpServletRequest request) {
		FileOutputStream fos = null;
		InputStream in = null;
		try {
			File file = new File("c:/bill.ag");
			in = request.getInputStream();

			fos = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int bytes = 0;
			while ((bytes = in.read(buffer)) != -1) {
				fos.write(buffer, 0, bytes);
			}

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

			if (fos != null) {
				try {
					fos.flush();
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

 

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值