使用JavaApi实现发送Http请求

	/**
	 * 发送HTTP请求
	 * 
	 * @param path
	 *            请求地址
	 * @param body
	 *            请求体
	 * @param method
	 *            请求方式GET/POST
	 * @param charset
	 *            请求编码格式
	 * @param header
	 *            请求头
	 * @param readTimeout
	 *            请求超时时间
	 * @param connectTimeout
	 *            连接超时时间
	 * @param doOutput
	 *            是否可写
	 * @param doInput
	 *            是否可读
	 * @param contentType
	 *            请求contentType
	 * @return
	 * @throws IOException
	 */
	public static ByteArrayOutputStream sendHttpRequest(String path,
			String body, String method, String charset,
			Map<String, String> header, int readTimeout, int connectTimeout,
			boolean doOutput, boolean doInput, String contentType)
			throws Exception {
		HttpURLConnection httpURLConnection = null;
		InputStream in = null;
		ByteArrayOutputStream baos = null;
		// URL转译
		int index = path.indexOf("?");
		if (index != -1) {
			String urlStr = path.substring(0, index + 1);
			String param = path.substring(index + 1);
			param = URLEncode(param, charset);
			path = urlStr + param;
		}
		// System.out.println("====>url: " + path);
		URL url = new URL(path);
		httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection.setRequestMethod(method);
		httpURLConnection.setReadTimeout(readTimeout);
		httpURLConnection.setConnectTimeout(connectTimeout);
		httpURLConnection.setDoOutput(doOutput);// 打开写入属性
		httpURLConnection.setDoInput(doInput);// 打开读取属性
		if (null != contentType && !"".equals(contentType.trim())) {
			httpURLConnection.setRequestProperty("Content-Type", contentType);
		}
		// 设置header
		httpURLConnection = setRequestHeader(httpURLConnection, header);
		httpURLConnection.connect(); // 连接
		if (!"GET".equalsIgnoreCase(method)) {
			body = URLEncode(body, charset);
			// System.out.println("====>body: " + body);
			httpURLConnection.getOutputStream().write(body.getBytes(charset));
		}
		int status = httpURLConnection.getResponseCode();
		System.out.println("urlparam=" + path.substring(path.indexOf("?") + 1)
				+ ", param=" + body + ", responseCode=" + status);
		if (200 == status) {
			in = (InputStream) httpURLConnection.getContent();
			baos = convert(in);
		} else {
			// System.out.println("====>response status: " + status);
			new Exception("responseCode is " + status);
		}
		if (httpURLConnection != null)
			httpURLConnection.disconnect();// 断开连接
		return baos;
	}



请求参数转译,将请求参数中的除了"&" 和 "="的字符进行url转译,当参数中包含"&"时必须在拼装参数之前进行转译,并且在接收到请求之后手工转回"&"

	public static final String EQUAL = "=";
	public static final String AND = "&";
	public static final String PREFIX = "*_*";
	public static final String SUFFIX = "_*_";
	public static final String EQUAL_PS = PREFIX + EQUAL + SUFFIX;
	public static final String AND_PS = PREFIX + AND + SUFFIX;

	/**
	 * 将参数按照指定编码格式进行URL转换
	 * 
	 * @param body
	 * @param charset
	 * @return
	 */
	public static String URLEncode(String body, String charset) {
		if (null == body || "".equals(body) || "".equals(body.trim())) {
			return "";
		}
		try {
			String equalEncode = URLEncoder.encode(EQUAL_PS, charset);
			String andEncode = URLEncoder.encode(AND_PS, charset);
			body = body.replace(EQUAL, EQUAL_PS);
			body = body.replace(AND, AND_PS);
			body = URLEncoder.encode(body, charset);
			body = body.replace(equalEncode, EQUAL);
			body = body.replace(andEncode, AND);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		// System.out.println("==>URLEncode: " + body);
		return body;
	}


由于某些地方肯能会重复使用响应的InputStream,并且,当连接关闭后,不能再读取响应的InputStream,

因此需要将InputStream转换成ByteArrayOutputStream,在使用的时候将ByteArrayOutputStream转回InputStream就行了

	/**
	 * 将respon转换为中间变量,解决由于http连接关闭导致inputStream关闭,从而不能读取的问题
	 * 
	 * @param in
	 * @return
	 * @throws Exception
	 */
	public static ByteArrayOutputStream convert(InputStream in)
			throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len;
		while ((len = in.read(buffer)) > -1) {
			baos.write(buffer, 0, len);
		}
		baos.flush();
		return baos;
	}

	/**
	 * 将中间变量还原为为请求response的inputStream
	 * 
	 * @param baos
	 * @return
	 */
	public static InputStream convert(ByteArrayOutputStream baos)
			throws Exception {
		return new ByteArrayInputStream(baos.toByteArray());
	}


对于http请求的其他固定参数,可以自定义枚举类型来处理,例如Content-type  和Charset

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值