java http请求工具类


import java.io.BufferedReader;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.stream.Collectors;

public class NetworkUtil {
	public static String sendPost(String pathUrl, Map<String, Object> param) {
		StringBuffer result = new StringBuffer();
		HttpURLConnection httpConn = null;
		DataOutputStream dos = null;
		BufferedReader responseReader = null;
		try {
			URL url = new URL(pathUrl);
			httpConn = (HttpURLConnection) url.openConnection();

			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestMethod("POST");
			StringBuffer requestString = new StringBuffer("");
			if (param != null && !param.isEmpty()) {
				for (String key : param.keySet()) {
					requestString.append("&").append(key).append("=").append(param.get(key));
				}
			}

			httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", "UTF-8");

			dos = new DataOutputStream(httpConn.getOutputStream());
			dos.writeBytes(requestString.toString());
			dos.flush();

			int responseCode = httpConn.getResponseCode();

			if (HttpURLConnection.HTTP_OK == responseCode) {
				String readLine;
				responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
				while ((readLine = responseReader.readLine()) != null) {
					result.append(readLine);
				}
			}
		} catch (Exception e) {

		} finally {
			if (httpConn != null)
				httpConn.disconnect();
			close(dos);
			close(responseReader);
		}
		return result.toString();
	}

	public static String sendGet(String url, Map<String, Object> param) {
		String result = "";
		BufferedReader in = null;
		try {
			StringBuffer requestString = new StringBuffer("");
			if (param != null && !param.isEmpty()) {
				for (String key : param.keySet()) {
					requestString.append("&").append(key).append("=").append(param.get(key));
				}
			}
			String urlNameString = url
					+ (requestString.length() > 0 ? "?" + requestString.substring(1).toString() : "");

			URL realUrl = new URL(urlNameString);

			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
	
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	
			connection.connect();
		
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {

		} finally {
			close(in);
		}
		return result;
	}


	public static String sendJsonForWeixin(String pathUrl, String jsonStr) {
		StringBuffer result = new StringBuffer();
		HttpURLConnection httpConn = null;
		BufferedReader responseReader = null;
		PrintWriter out = null;
		try {
			URL url = new URL(pathUrl);
			httpConn = (HttpURLConnection) url.openConnection();

			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestMethod("POST");
			httpConn.setRequestProperty("Content-Type", "application/json");
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", "UTF-8");

			
			OutputStreamWriter outWriter = new OutputStreamWriter(httpConn.getOutputStream(), "utf-8");
			out = new PrintWriter(outWriter);
		
			out.print(jsonStr);
	
			out.flush();

			int responseCode = httpConn.getResponseCode();

			if (HttpURLConnection.HTTP_OK == responseCode) {
				String readLine;
				responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
				while ((readLine = responseReader.readLine()) != null) {
					result.append(readLine);
				}
			}
		} catch (Exception e) {

		} finally {
			if (httpConn != null)
				httpConn.disconnect();
			close(responseReader);
			close(out);
		}
		return result.toString();
	}


	public static String sendJsonByWriter(String pathUrl, String jsonStr) {
		StringBuffer result = new StringBuffer();
		HttpURLConnection httpConn = null;
		BufferedReader responseReader = null;
		PrintWriter out = null;
		try {
			URL url = new URL(pathUrl);
			httpConn = (HttpURLConnection) url.openConnection();

			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestMethod("POST");
			httpConn.setRequestProperty("Content-Type", "application/json");
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", "UTF-8");

			
			OutputStreamWriter outWriter = new OutputStreamWriter(httpConn.getOutputStream(), "utf-8");
			out = new PrintWriter(outWriter);
	
			out.print(jsonStr);
			
			out.flush();

			int responseCode = httpConn.getResponseCode();

			if (HttpURLConnection.HTTP_OK == responseCode) {
				String readLine;
				responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
				while ((readLine = responseReader.readLine()) != null) {
					result.append(readLine);
				}
			}
		} catch (Exception e) {

		} finally {
			if (httpConn != null)
				httpConn.disconnect();
			close(responseReader);
			close(out);
		}
		return result.toString();
	}

	public static String sendJson(String pathUrl, String jsonStr) {
		HttpURLConnection httpConn = null;
		try {
			URL url = new URL(pathUrl);
			httpConn = (HttpURLConnection) url.openConnection();

			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestMethod("POST");

			httpConn.setRequestProperty("Content-Type", "application/json");
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", "UTF-8");

			httpConn.getOutputStream().write(jsonStr.getBytes("utf-8"));

			int responseCode = httpConn.getResponseCode();

			String response = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8")).lines()
					.collect(Collectors.joining());

			if (HttpURLConnection.HTTP_OK != responseCode) {
				throw new RuntimeException("请求返回状态码为:" + responseCode + ",响应内容:" + response + ",没有处理流程");
			}

			return response;
		} catch (Exception e) {
			throw new RuntimeException("发送Json请求错误", e);
		} finally {
			if (httpConn != null)
				httpConn.disconnect();
		}
	}

	public static void close(Closeable obj) {
		try {
			obj.close();
		} catch (Exception e) {
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值