HttpUtil.java 9.4 KB
package com.espeed.reading.util;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


/**
 * 
 * @项目名称: 鹰眼搜搜索系统
 * @版权所有: 深圳市科飞时速网络技术有限公司(0755-88843776)
 * @技术支持: info@21gmail.com
 * @单元名称: http协议GET/POST请求工具类
 * @开始时间: 2017-10-14
 * @开发人员: 杨志钊
 */
public class HttpUtil {
	
	public static void main(String[] args) {
		Map<String, Object> params = new HashMap<String, Object>();
		
		params.put("ip", "183.15.151.144");
		
		System.out.println(doGet("http://115.29.230.132:85/webservice/ip", params));
	}

	private final static int timeOut = 60 * 1000;

	/** POST请求 */
	public static Map<String, Object> doPost(String url, Map<String, Object> params) {

		Map<String, Object> result = new HashMap<String, Object>();
		result.put("responseCode", 100);
		result.put("success", true);
		result.put("data", null);
		result.put("code", 200);
		result.put("msg", null);

		HttpURLConnection httpUrlConnection = null;
		OutputStream out = null;
		DataOutputStream dataOutputStream = null;
		InputStream in = null;
		ByteArrayOutputStream baos = null;
		try {
			URLConnection urlConnection = new URL(url).openConnection();
			httpUrlConnection = (HttpURLConnection) urlConnection;
			// 设置是否向httpUrlConnection输出,post请求,参数要放在http正文内,因此需要设为true,
			// 默认情况下是false;
			httpUrlConnection.setDoOutput(true);
			// 设置是否从httpUrlConnection读入,默认情况下是true;
			httpUrlConnection.setDoInput(true);
			// 忽略缓存
			httpUrlConnection.setUseCaches(false);
			// 设定请求的方法为"POST",默认是GET
			httpUrlConnection.setRequestMethod("POST");

			// 设置连接主机超时(单位:毫秒)
			httpUrlConnection.setConnectTimeout(timeOut);
			// 设置从主机读取数据超时(单位:毫秒)
			httpUrlConnection.setReadTimeout(timeOut);

			httpUrlConnection.connect();

			// 建立输入流,向指向的URL传入参数

			String queryString = "";

			if (params != null) {
				String value;
				for (String key : params.keySet()) {
					value = "";
					if (params.get(key) != null) {
						value = params.get(key).toString();
					}
					queryString += key + "="
							+ URLEncoder.encode(value.toString(), "UTF-8")
							+ "&";
				}
			}

			if (queryString.length() > 0) {
				queryString = queryString
						.substring(0, queryString.length() - 1);
				out = httpUrlConnection.getOutputStream();
				dataOutputStream = new DataOutputStream(out);
				dataOutputStream.writeBytes(queryString);

				dataOutputStream.flush();
				out.flush();
			}

			// 获得响应状态
			int responseCode = httpUrlConnection.getResponseCode();
			result.put("responseCode", responseCode);

			if (HttpURLConnection.HTTP_OK == responseCode) {
				baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				in = httpUrlConnection.getInputStream();
				while ((len = in.read(buffer)) != -1) {
					baos.write(buffer, 0, len);
					baos.flush();
				}

				result.put("success", true);
				result.put("data", baos.toString("UTF-8"));
				result.put("code", 200);
				result.put("msg", "请求成功。");
			} else {
				result.put("success", false);
				result.put("code", 502);
				result.put("msg", "请求异常,请求响应码是" + responseCode + "。");

				baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				in = httpUrlConnection.getInputStream();
				if (in != null) {
					while ((len = in.read(buffer)) != -1) {
						baos.write(buffer, 0, len);
						baos.flush();
					}
					String str = baos.toString("UTF-8");
					if (str.trim().length() > 0) {
						result.put("msg", result.get("msg") + str);
					}
				}
			}
		} catch (SocketTimeoutException e) {
			result.put("success", false);
			result.put("code", 501);
			result.put("msg", "请求超时,若是多次尝试后仍然无法请求,请联系客服。");
		} catch (Exception e) {
			result.put("success", false);
			result.put("code", 500);
			result.put("msg",
					"请求异常,异常信息:" + e.getClass() + "->" + e.getMessage());
		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					result.put("success", false);
					result.put("code", 500);
					result.put("msg",
							"请求异常,异常信息:" + e.getClass() + "->" + e.getMessage());
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					result.put("success", false);
					result.put("code", 500);
					result.put("msg",
							"请求异常,异常信息:" + e.getClass() + "->" + e.getMessage());
				}
			}
			if (dataOutputStream != null) {
				try {
					dataOutputStream.close();
				} catch (IOException e) {
					result.put("success", false);
					result.put("code", 500);
					result.put("msg",
							"请求异常,异常信息:" + e.getClass() + "->" + e.getMessage());
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					result.put("success", false);
					result.put("code", 500);
					result.put("msg",
							"请求异常,异常信息:" + e.getClass() + "->" + e.getMessage());
				}
			}
			if (httpUrlConnection != null) {
				httpUrlConnection.disconnect();
			}
		}

		return result;
	}

	/** GET请求 */
	public static Map<String, Object> doGet(String url, Map<String, Object> params) {

		Map<String, Object> result = new HashMap<String, Object>();
		result.put("responseCode", 100);
		result.put("success", true);
		result.put("data", null);
		result.put("code", 200);
		result.put("msg", null);

		HttpURLConnection httpUrlConnection = null;
		InputStream in = null;
		ByteArrayOutputStream baos = null;

		try {
			// URL传入参数
			String queryString = "";

			if (params != null) {
				String value;
				for (String key : params.keySet()) {
					value = "";
					if (params.get(key) != null) {
						value = params.get(key).toString();
					}
					queryString += key + "="
							+ URLEncoder.encode(value.toString(), "UTF-8")
							+ "&";
				}
			}

			if (queryString.length() > 0) {
				queryString = queryString
						.substring(0, queryString.length() - 1);

				url = url + "?" + queryString;
			}

			URLConnection urlConnection = new URL(url).openConnection();
			httpUrlConnection = (HttpURLConnection) urlConnection;
			// 设置是否向httpUrlConnection输出,post请求,参数要放在http正文内,因此需要设为true,
			// 默认情况下是false;
			httpUrlConnection.setDoOutput(false);
			// 设置是否从httpUrlConnection读入,默认情况下是true;
			httpUrlConnection.setDoInput(true);
			// 忽略缓存
			httpUrlConnection.setUseCaches(false);
			// 设定请求的方法为"POST",默认是GET
			httpUrlConnection.setRequestMethod("GET");

			// 设置连接主机超时(单位:毫秒)
			httpUrlConnection.setConnectTimeout(timeOut);
			// 设置从主机读取数据超时(单位:毫秒)
			httpUrlConnection.setReadTimeout(timeOut);

			httpUrlConnection.connect();

			// 获得响应状态
			int responseCode = httpUrlConnection.getResponseCode();
			result.put("responseCode", responseCode);
			
			if (HttpURLConnection.HTTP_OK == responseCode) {
				baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				in = httpUrlConnection.getInputStream();
				while ((len = in.read(buffer)) != -1) {
					baos.write(buffer, 0, len);
					baos.flush();
				}

				result.put("success", true);
				result.put("data", baos.toString("UTF-8"));
				result.put("code", 200);
				result.put("msg", "请求成功。");
			} else {
				result.put("success", false);
				result.put("code", 502);
				result.put("msg", "请求异常,请求响应码是" + responseCode + "。");

				baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				in = httpUrlConnection.getInputStream();
				if (in != null) {
					while ((len = in.read(buffer)) != -1) {
						baos.write(buffer, 0, len);
						baos.flush();
					}
					String str = baos.toString("UTF-8");
					if (str.trim().length() > 0) {
						result.put("msg", result.get("msg") + str);
					}
				}

			}
		} catch (SocketTimeoutException e) {
			result.put("success", false);
			result.put("code", 501);
			result.put("msg", "请求超时,若是多次尝试后仍然无法请求,请联系客服。");
		} catch (Exception e) {
			result.put("success", false);
			result.put("code", 500);
			result.put("msg",
					"请求异常,异常信息:" + e.getClass() + "->" + e.getMessage());
		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					result.put("success", false);
					result.put("code", 500);
					result.put("msg",
							"请求异常,异常信息:" + e.getClass() + "->" + e.getMessage());
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					result.put("success", false);
					result.put("code", 500);
					result.put("msg",
							"请求异常,异常信息:" + e.getClass() + "->" + e.getMessage());
				}
			}

			if (httpUrlConnection != null) {
				httpUrlConnection.disconnect();
			}
		}

		return result;
	}

}