java自带的http工具

  |   0 评论   |   0 浏览
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;

/**
 * HttpUtils
 * 
 * @author pengzai
 *
 */
public class HttpUtils {
	private static final String CTYPE_FORM = "application/x-www-form-urlencoded;charset=utf-8";
	private static final String CTYPE_JSON = "application/json;charset=utf-8";
	private static final String charset = "utf-8";
	private static final int CONNECT_TIMEOUT = 15000;
	private static final int READ_TIMEOUT = 15000;
	private static final String METHOD_POST = "POST";
	
	
	public static String postJson(String url, String jsonContent) throws Exception {
		return doRequest(METHOD_POST, url, jsonContent,CTYPE_JSON);
	}

	public static String postForm(String url, Map<String, Object> params) throws Exception {
		return doRequest(METHOD_POST, url, buildQuery(params),CTYPE_FORM);
	}
	
	private static String doRequest(String method, String url, String requestContent, String ctype) throws Exception {
		HttpURLConnection conn = null;
		OutputStream out = null;
		String rsp = null;
		try {
			conn = getConnection(new URL(url), method, ctype);

			if (requestContent != null && requestContent.trim().length() > 0) {
				out = conn.getOutputStream();
				out.write(requestContent.getBytes(charset));
			}

			rsp = getResponseAsString(conn);
		} finally {
			if (out != null) {
				out.close();
			}
			if (conn != null) {
				conn.disconnect();
			}
			conn = null;
		}
		return rsp;
	}
	
	private static HttpURLConnection getConnection(URL url, String method, String ctype)
			throws IOException {
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod(method);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", ctype);
		conn.setConnectTimeout(CONNECT_TIMEOUT);
		conn.setReadTimeout(READ_TIMEOUT);
		return conn;
	}
	
	private static String getResponseAsString(HttpURLConnection conn) throws Exception {
		InputStream es = conn.getErrorStream();
		if (es == null) {
			return getStreamAsString(conn.getInputStream(), charset, conn);
		} else {
			String msg = getStreamAsString(es, charset, conn);
			if (msg != null && msg.trim().length() > 0) {
				throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
			} else {
				return msg;
			}
		}
	}
	
	private static String getStreamAsString(InputStream stream, String charset, HttpURLConnection conn) throws Exception {
		try {
			Reader reader = new InputStreamReader(stream, charset);

			StringBuilder response = new StringBuilder();
			final char[] buff = new char[1024];
			int read = 0;
			while ((read = reader.read(buff)) > 0) {
				response.append(buff, 0, read);
			}

			return response.toString();
		} finally {
			if (stream != null) {
				stream.close();
			}
		}
	}
	
	private static String buildQuery(Map<String, Object> params) throws Exception {
		if (params == null || params.isEmpty()) {
			return "";
		}

		StringBuilder query = new StringBuilder();
		Set<Map.Entry<String, Object>> entries = params.entrySet();
		boolean hasParam = false;

		for (Map.Entry<String, Object> entry : entries) {
			String name = entry.getKey();
			String value = String.valueOf(entry.getValue());
			if (hasParam) {
				query.append("&");
			} else {
				hasParam = true;
			}
			query.append(name).append("=").append(URLEncoder.encode(value, charset));
		}
		return query.toString();
	}

}