一、前言
基于java.net.*、java.io.*、java.nio.*开发包定义http协议工具类HttpUtils,进行基于http协议常见数据包文请求类型FormPost/XmlPost/JsonPost/HttpGo等操作代码示例,详情参见代码示例。
二、代码示例import java.io.InputStream;@b@import java.io.OutputStream;@b@import java.net.HttpURLConnection;@b@import java.net.URL;@b@import java.net.URLEncoder;@b@import java.nio.charset.Charset;@b@import java.util.Arrays;@b@import java.util.HashMap;@b@import java.util.Map;@b@@b@import com.alibaba.fastjson.JSONObject;@b@import com.alibaba.fastjson.serializer.SerializerFeature;@b@@b@public class HttpUtils {@b@@b@public static String METHOD_GET = "GET";@b@public static String METHOD_POST = "POST";@b@@b@public static int DEF_CONNECT_TIMEOUT = 5 * 1000;@b@public static int DEF_READ_TIMEOUT = 25 * 1000;@b@public static Charset DEF_CHARSET = Charset.forName("UTF-8");@b@@b@public static String Get(String urlString) throws Exception {@b@return HttpGo(urlString, METHOD_GET, null, null, DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);@b@}@b@@b@public static String Get(String urlString, Map headers) throws Exception {@b@return HttpGo(urlString, METHOD_GET, headers, null, DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);@b@}@b@@b@public static String Get(String urlString, Map headers, Map params) throws Exception {@b@if (params != null && params.isEmpty() == false) {@b@StringBuffer url = new StringBuffer(urlString);@b@try {@b@boolean isFirst = true;@b@if (urlString.contains("?")) {@b@if (urlString.endsWith("&") == false && urlString.contains("&")) {@b@isFirst = false;@b@}@b@} else {@b@url.append('?');@b@}@b@String paramsEncoding = DEF_CHARSET.name();@b@for (Map.Entry entry : params.entrySet()) {@b@if (isFirst) isFirst = false; else url.append('&');@b@url.append(URLEncoder.encode(entry.getKey(), paramsEncoding));@b@url.append('=');@b@url.append(URLEncoder.encode(entry.getValue(), paramsEncoding));@b@}@b@} catch (Exception e) {@b@}@b@return Get(url.toString(), headers);@b@} else {@b@return Get(urlString, headers);@b@}@b@}@b@@b@public static String Post(String urlString, String contentType, byte[] content) throws Exception {@b@Map headers = new HashMap(1);@b@headers.put("Content-Type", contentType);@b@return HttpGo(urlString, METHOD_POST, headers, content, DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);@b@}@b@@b@public static String FormPost(String urlString, String content) throws Exception {@b@Map headers = new HashMap(1);@b@headers.put("Content-Type", String.format("application/x-www-form-urlencoded; charset=%s", DEF_CHARSET.name()));@b@return HttpGo(urlString, METHOD_POST, null, content.getBytes(DEF_CHARSET), DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);@b@}@b@@b@public static String XmlPost(String urlString, String content) throws Exception {@b@Map headers = new HashMap(1);@b@headers.put("Content-Type", String.format("text/html; charset=%s", DEF_CHARSET.name()));@b@return HttpGo(urlString, METHOD_POST, headers, content.getBytes(DEF_CHARSET), DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);@b@}@b@@b@public static String JsonPost(String urlString, Object content) throws Exception {@b@return JsonPost(urlString, JSONObject.toJSONString(content, SerializerFeature.DisableCircularReferenceDetect));@b@}@b@@b@public static String JsonPost(String urlString, String content) throws Exception {@b@Map headers = new HashMap(1);@b@headers.put("Content-Type", String.format("application/json; charset=%s", DEF_CHARSET.name()));@b@return HttpGo(urlString, METHOD_POST, headers, content.getBytes(DEF_CHARSET), DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);@b@}@b@@b@public static String JsonPost(String urlString, String content, int readTimeout) throws Exception {@b@Map headers = new HashMap(1);@b@headers.put("Content-Type", String.format("application/json; charset=%s", DEF_CHARSET.name()));@b@return HttpGo(urlString, METHOD_POST, headers, content.getBytes(DEF_CHARSET), DEF_CONNECT_TIMEOUT, readTimeout);@b@}@b@@b@public static String HttpGo(String urlString, String method, Map headers, byte[] content, int connectTimeout, int readTimeout) throws Exception {@b@HttpURLConnection conn = null;@b@try { @b@conn = (HttpURLConnection) new URL(urlString).openConnection(); @b@conn.setRequestMethod(method); @b@conn.setDoOutput(true); @b@conn.setDoInput(true); @b@conn.setUseCaches(false);@b@conn.setConnectTimeout(connectTimeout);@b@conn.setReadTimeout(readTimeout);@b@@b@if (headers != null) {@b@for (Map.Entry entry : headers.entrySet()) {@b@conn.addRequestProperty(entry.getKey(), entry.getValue());@b@}@b@}@b@if (content != null) {@b@if (headers == null || headers.containsKey("Content-Length") == false) {@b@conn.addRequestProperty("Content-Length", Integer.toString(content.length));@b@}@b@OutputStream output = null;@b@try {@b@output = conn.getOutputStream();@b@output.write(content); @b@output.flush(); @b@} finally {@b@if (output != null) try { output.close(); } catch (Exception e) { }@b@}@b@}@b@return readContent(conn.getResponseCode() == 200 ? conn.getInputStream() : conn.getErrorStream(), getCharset(conn));@b@} finally { @b@if (conn != null) conn.disconnect(); @b@} @b@}@b@@b@public static String encodeParams(Map params, String paramsEncoding) throws Exception {@b@boolean isFirst = true;@b@StringBuilder encodedParams = new StringBuilder();@b@for (Map.Entry entry : params.entrySet()) {@b@if (isFirst) isFirst = false; else encodedParams.append('&');@b@encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));@b@encodedParams.append('=');@b@encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));@b@}@b@return encodedParams.toString();@b@}@b@@b@public static volatile String CHARSET_DEF = DEF_CHARSET.name();@b@private static String CHARSET_STR = "charset=";@b@private static int CHARSET_STR_LEN = CHARSET_STR.length();@b@private static String getCharset(HttpURLConnection conn) {@b@String contentType = conn.getHeaderField("Content-Type");@b@int length = contentType != null ? contentType.length() : 0;@b@if (length = data.length) {@b@data = Arrays.copyOf(data, offset + APPEND_LEN);@b@}@b@}@b@return charset != null ? new String(data, 0, offset, charset) : new String(data, 0, offset);@b@} finally {@b@if (input != null) try { input.close(); } catch (Exception e) { }@b@}@b@}@b@}