HttpURLConnection原生JAVA http請求

场景:做开发很久了,每次进行http请求都要去找依赖包,非常不爽,所以直接自己搞一个简易的;当然论稳定性,和适用性肯定没有那些千锤百炼的第三方高,不过谁让我有强迫症呢,只要有自己的东西,就不想用别人的了,哪怕比我好



import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;

/**
 * http请求
 * 
 * @author taihei
 *
 */
public class MyHttpReq {
	
	/**
	 * http请求
	 * 
	 * @param uri
	 * @param method
	 *            请求方式(get/post)默认get 可为null
	 * @param params
	 *            参数 可为null
	 * @param charSet
	 *            默认 utf8 可为 null
	 * @return
	 * 			若请求失败,则返回以 "错误:"为开头的字符串
	 */
	public static String httpReq(String uri, String method, Map<String, Object> params, String charSet) {
		
		if (null == uri || uri.replace(" ", "").length() < 12 || !uri.startsWith("http://")) {//一个合法的网址至少为12位(需以http开头)
			return "错误:URI非法";
		}
		
		// 判断是否有指定请求方式 如果没有指定请求方式 则默认get请求
		if (null == method || method.replace("", "").length() < 3) {
			method = "get";
		}
		if (null == charSet || charSet.replace(" ", "").length() < 3) {// 最短的编码是gbk
																		// 3位
			charSet = "utf8";
		}
		method = method.toUpperCase();
		if (method.equalsIgnoreCase("get")) {
			// 对参数进行处理
			if (null != params && params.size() > 0) {
				Set<String> ks = params.keySet();
				StringBuilder sb = new StringBuilder();
				for (String key : ks) {
					try {
						sb.append(key + "=" + URLEncoder.encode(params.get(key).toString(), charSet) + "&");//内容用url编码
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
				String pj = sb.substring(0, sb.length() - 1);
				if (pj.length() > 0) {
					if (uri.contains("?")) {
						uri = uri + "&" + pj;
					} else {
						uri = uri + "?" + pj;
					}
				}
			}

			try {
				URL url = new URL(uri);
				// 打开连接 HttpURLConnection是URLConnection的子类
				HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
				//默认返回值格式为json
				urlConnection.setRequestProperty("Accept", "application/json");
				if (200 == urlConnection.getResponseCode()) {
					// 得到输入流
					InputStream is = urlConnection.getInputStream();
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					byte[] buffer = new byte[1024];
					int len = 0;
					while (-1 != (len = is.read(buffer))) {
						baos.write(buffer, 0, len);
						baos.flush();
					}

					urlConnection.disconnect();// 数据读取完毕关闭流
					return baos.toString("utf-8");
				} else {
					return "错误:网络异常";
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (method.equalsIgnoreCase("post")) {
			try {
				URL url = new URL(uri);
				// 打开连接 HttpURLConnection是URLConnection的子类
				HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
				urlConnection.setRequestMethod(method);
				// conn.setConnectTimeout(10000);//连接超时 单位毫秒
				// conn.setReadTimeout(2000);//读取超时 单位毫秒
				// 发送POST请求必须设置如下两行
				urlConnection.setDoOutput(true);
				urlConnection.setDoInput(true);
//				urlConnection.setRequestProperty("Accept", "application/xhtml+xml");//xml格式返回值
				//默认返回值格式为json
				urlConnection.setRequestProperty("Accept", "application/json");
				urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				// 如果需要发送数据
				if (null != params && params.size() > 0) {
					// 获取URLConnection对象对应的输出流
					PrintWriter printWriter = new PrintWriter(urlConnection.getOutputStream());
					// 发送请求参数
					printWriter.write(params.toString().replaceAll("[{|}]", ""));
					// flush输出流的缓冲
					printWriter.flush();
				}
				if (200 == urlConnection.getResponseCode()) {
					// 得到输入流
					InputStream is = urlConnection.getInputStream();
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					byte[] buffer = new byte[1024];
					int len = 0;
					while (-1 != (len = is.read(buffer))) {
						baos.write(buffer, 0, len);
						baos.flush();
					}
					urlConnection.disconnect();// 数据读取完毕关闭流
					return baos.toString("utf-8");
				} else {
					return "错误:网络异常";
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return "错误:请求失败";
	}
}

 

转载于:https://my.oschina.net/2892328252/blog/993734

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值