HttpURLConnHelper

本文介绍了一个用于从URL加载流和字节的HTTP URL连接助手类,包括加载流的方法和加载字节的方法,以及POST提交数据的方法。

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

package com.shanhw.practice;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnHelper {

	/**
	 * @param url
	 * @return 返回一个InputStream
	 */
	public static InputStream loadStreamFromURL(String url) {
		BufferedInputStream bis = null;
		HttpURLConnection httpConn = null;
		URL urlObj;
		try {
			urlObj = new URL(url);
			httpConn = (HttpURLConnection) urlObj.openConnection();
			if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				bis = new BufferedInputStream(httpConn.getInputStream());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
				if (httpConn != null) {
					httpConn.disconnect();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return bis;
	}

	/**
	 * @param url
	 * @return 返回一个byte[]
	 */
	public static byte[] loadByteFromURL(String url) {

		byte[] byteObj = null;
		HttpURLConnection httpConn = null;
		URL urlObj;
		try {
			urlObj = new URL(url);
			httpConn = (HttpURLConnection) urlObj.openConnection();
			if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				IOHelper io = new IOHelper();
				byteObj = io.streamToByte(httpConn.getInputStream());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (httpConn != null) {
				httpConn.disconnect();
			}
		}
		return byteObj;
	}

	/**
	 * @param url
	 * @param parameters
	 * @return
	 */
	public static String doPostSubmit(String url, String parameters) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		URL urlObj = null;
		HttpURLConnection httpConn = null;

		String returnData = null;
		try {
			urlObj = new URL(url);
			httpConn = (HttpURLConnection) urlObj.openConnection();
			httpConn.setRequestMethod("POST");
			httpConn.setDoOutput(true);

			if (parameters != null) {
				bos = new BufferedOutputStream(httpConn.getOutputStream());
				bos.write(parameters.getBytes());
				bos.flush();
			}

			if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				bis = new BufferedInputStream(httpConn.getInputStream());
				IOHelper io = new IOHelper();
				returnData = io.streamToString(bis);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
				if (bos != null) {
					bos.close();
				}
				httpConn.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return returnData;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值