Java客户端通过Http发送POST请求上传文件到web服务器

通过HttpURLConnection类实现http协议上传信息

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import com.sys.common.log.Log;

/**
 * 
 */

/**
 * 使用HttpURLConnection对象模拟测试后台接口
 * @author
 *
 */
public class MyHttpURLConnection {
	
	private static String HTTP_URL="http://www.baidu.com";
	private static String	HTTP_METHOD_POST="POST";
	
	
	
	public static void main(String[] args) {
		
		 
		 try {
		System.out.println(	MyHttpURLConnection.sendHttp(""));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	
	
	/**
	 * 模拟HTTP 请求 提交普通数据
	 * 
	 * @param postData
	 *            发送数据
	 * @return
	 */
	private static String sendHttp(String postData) throws Exception {
		if (HTTP_URL == null || "".equals(HTTP_URL)) {
			throw new Exception("请传入远程请求地址");
		}
		String result = "";
		BufferedWriter out = null;
		BufferedInputStream reader = null;
		HttpURLConnection connection = null;
		try {
			URL u = new URL(HTTP_URL);
			connection = (HttpURLConnection) u.openConnection();
			int code;
			connection.setDoOutput(true);//是否向connection输出  
			connection.setUseCaches(false);//因为是post请求所以不能使用缓存
			connection.setConnectTimeout(120000); // 连接超时为120秒
			connection.setRequestMethod(HTTP_METHOD_POST);
			//告诉服务端 要发送数据的长度
			connection.setRequestProperty("Content-Length",
					postData.getBytes("UTF-8").length + "");
			//告诉服务器客户端浏览器内核
			connection.setRequestProperty("User-Agent", "Mozilla/4.0");
			//告诉服务器 要发送数据的格式和字符编码
			connection.setRequestProperty("Content-Type",
					"text/xml;charset=UTF-8");
			//通过connection连接对象获取输出流对象
			out = new BufferedWriter(new OutputStreamWriter(
					connection.getOutputStream(), "UTF-8"));
			//将需要想客户端发送的信息写入到输出流  刷新输出流并且关闭流
			out.write(postData);
			out.flush();
			out.close();
			out = null;
			code = connection.getResponseCode();
			if (code == HttpURLConnection.HTTP_OK) {
				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				reader = new BufferedInputStream(connection.getInputStream());
				int b;
				byte[] bit = new byte[1024];
				while (-1 != (b = reader.read(bit))) {
					byteArrayOutputStream.write(bit, 0, b);
				}
				result = new String(byteArrayOutputStream.toByteArray());
			} else {
				Log.error("post ResponseCode=" + connection.getResponseCode());
				Log.error("post ResponseMessage="
						+ connection.getResponseMessage());
				reader = new BufferedInputStream(connection.getErrorStream());
				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				int b;
				byte[] bit = new byte[1024];
				while (-1 != (b = reader.read(bit))) {
					byteArrayOutputStream.write(bit, 0, b);
				}
				result = new String(byteArrayOutputStream.toByteArray());
				throw new Exception("服务端发生异常");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
			if (reader != null) {
				reader.close();
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return result;
	}

}


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值