Java工具类-http请求相关

http请求相关


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyHttpUtils {

	private MyHttpUtils() {
		throw new IllegalStateException("MyHttpUtils class");
	}

	public static String encodeURL(String url, String charset) {
		try {
			url = URLEncoder.encode(url, charset);
		} catch (UnsupportedEncodingException ex) {
			log.error(ex.getMessage());
		}
		return url;
	}

	/**
	 * 向指定URL发送GET请求(参数都在URL上的).
	 * URLConnection是所有类的超类,应用程序和URL之间的通信链接.用字节流输出OutputStreamWriter/输入InputStreamReader(当然字符流也可)处理的.
	 * @param path
	 * @return
	 */
	public static String getData(String path) {
		if (StringUtils.isNotBlank(path)) {
			StringBuilder result = new StringBuilder();
			BufferedReader br = null;
			try {
				URL url = new URL(path);
				// URLConnection conn = url.openConnection(); //打开和URL之间的连接
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("GET"); // 请求的方式,默认GET
				conn.setConnectTimeout(5000); // milliseconds
				conn.setReadTimeout(5000); // milliseconds
				conn.setDoInput(true); // 是否打开输入流 ,默认true
				conn.setDoOutput(true); // 是否打开输出流,默认false
				conn.connect(); // 连接
				if (conn.getResponseCode() == 200) { // HTTP_OK
					// 定义BufferedReader输入流来读取URL的响应
					br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
					String line;
					while ((line = br.readLine()) != null) {
						result.append(line.trim()); // result += "\n" +line
					}
					// 下面是与上面功能另方法读取,推荐上述方法
					// InputStream inputStream = conn.getInputStream();
					// int size = inputStream.available();
					// byte[] bytes = new byte[size];
					// inputStream.read(bytes);
					// String result = new String(bytes, StandardCharsets.UTF_8);
				}
			} catch (IOException e) {
				log.error(e.getMessage());
			} finally {
				try {
					if (br != null)
						br.close();
				} catch (IOException ex) {
					log.error(ex.getMessage());
				}
			}
			return result.length() > 0 ?result.toString() :"";
		}
		return "";
	}

	/**
	 * 向指定URL发送POST请求(以UrlConnection连接方式).
	 * URLConnection是所有类的超类,应用程序和URL之间的通信链接.用字节流输出OutputStreamWriter/输入InputStreamReader(当然字符流也可)处理的.
	 * @param path        UNIFIED_ORDER_URL
	 * @param content
	 * @param contentType Example "user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)"
	 * @return
	 */
	public static String postData(String path, String content, String contentType) {
		if (StringUtils.isNotBlank(path) && StringUtils.isNotBlank(content)) {
			StringBuilder result = new StringBuilder();
			OutputStreamWriter osw = null;
			BufferedReader br = null;
			try {
				URL url = new URL(path);
				URLConnection conn = url.openConnection(); // 打开和URL之间的连接
				// 发送POST请求必须设置setDoOutput(true)和setDoInput(true)
				conn.setDoOutput(true); // post请求,参数要放在http正文内,因此需要设为true, 默认值为false.
				// conn.setDoInput(true); //设置是否从UrlConnection读入,默认值为true
				conn.setUseCaches(false); // Post请求不能使用缓存,默认值为true
				conn.setConnectTimeout(5000); // milliseconds
				conn.setReadTimeout(5000); // milliseconds
				if (StringUtils.isNotBlank(contentType))
					conn.setRequestProperty("content-type", contentType); // 设置内容类型

				// 获取URLConnection对象对应的输出流
				osw = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
				osw.write(content);
				osw.flush();

				// 定义BufferedReader输入流来读取URL的响应
				br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
				String line;
				while ((line = br.readLine()) != null) {
					result.append(line.trim()); // result += "\n" +line
				}
			} catch (IOException e) {
				log.error(e.getMessage());
			} finally {
				try {
					if (osw != null)
						osw.close();
					if (br != null)
						br.close();
				} catch (IOException ex) {
					log.error(ex.getMessage());
				}
			}
			return result.length() > 0 ?result.toString() :"";
		}
		return "";
	}

	public static Map<String, String> getParams4Url(String url) {
		if (StringUtils.isNotBlank(url)) {
			String params = url.substring(url.indexOf("?") + 1, url.length());
			String[] arr = params.split("&");
			int arrLen = arr.length;
			Map<String, String> rtnMap = new HashMap<>(arrLen);
			for (int i = 0; i < arrLen; i++) {
				String[] kvArr = arr[i].split("=");
				rtnMap.put(kvArr[0], (kvArr.length > 1 ?kvArr[1] :""));
			}
			return rtnMap;
		}
		return Collections.emptyMap();
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亚历山大伟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值