HttpHelper.java 15.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
package com.myproject.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.myproject.exception.ApiException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.Map.Entry;

/**
 * HTTP网络请求
 */
public class HttpHelper {
	// 编码方式
	private static final String CONTENT_CHARSET = "UTF-8";

	// 连接超时时间
	private static final int CONNECTION_TIMEOUT = 3000;

	// 读数据超时时间
	private static final int READ_DATA_TIMEOUT = 3000;

	// 设置User-Agent
	private static final String USER_AGENT = "SMD-BOX";

	public static String postJson(String url, Map<String, Object> params) throws ApiException {
		return postJson(url,params,null, "http");
	}

	public static String get(String url,HashMap<String, String> params) throws ApiException {
		return get(url,params,null, "http");
	}


	/**
	 * 向指定URL发送POST请求
	 * @param url
	 * @param paramMap
	 * @return 响应结果
	 */
	public static String postParam(String url, Map<String, Object> paramMap) throws ApiException {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// conn.setRequestProperty("Charset", "UTF-8");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());

			// 设置请求属性
			String param = "";
			if (paramMap != null && paramMap.size() > 0) {
				Iterator<String> ite = paramMap.keySet().iterator();
				while (ite.hasNext()) {
					String key = ite.next();// key
					Object valueObj = paramMap.get(key);
					String value = "";
					if(valueObj != null){
						if(valueObj instanceof Date){
							DateUtil.toDateString((Date)valueObj,"yyyyMMdd");
						}else{
							value = valueObj.toString();
						}
					}
					param += key + "=" + value + "&";
				}
				param = param.substring(0, param.length() - 1);
			}

			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				throw new ApiException("Request [" + url + "] close instream failed:" + ex.getMessage());
			}
		}
		return result;
	}

	/**
	 * 发送POST请求
	 * 
	 * @param url
	 *            请求URL地址
	 * @param params
	 *            请求参数
	 * @param protocol
	 *            请求协议 "http" / "https"
	 * @return 服务器响应的请求结果
	 */
	private static String postInBody(String url, HashMap<String, String> params,
			HashMap<String, String> cookies, String protocol) throws ApiException {
//		if (protocol.equalsIgnoreCase("https")) {
//			Protocol httpsProtocol = new Protocol("https", new SecureProtocolSocketFactoryImpl(), 443);
//			Protocol.registerProtocol("https", httpsProtocol);
//		}

		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(url);

		// 设置请求参数
		if (params != null && !params.isEmpty()) {
			NameValuePair[] data = new NameValuePair[params.size()];
			Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
			int i = 0;
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				data[i] = new NameValuePair(entry.getKey(), entry.getValue());
				++i;
			}
			postMethod.setRequestBody(data);
		}

		// 设置cookie
		if (cookies != null && !cookies.isEmpty()) {
			Iterator<Entry<String, String>> iterator = cookies.entrySet().iterator();
			StringBuilder buffer = new StringBuilder(128);
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				buffer.append(entry.getKey()).append("=").append(entry.getValue()).append("; ");
			}
			// 设置cookie策略
			postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
			// 设置cookie内容
			postMethod.setRequestHeader("Cookie", buffer.toString());
		}

		// 设置User-Agent
		postMethod.setRequestHeader("User-Agent", USER_AGENT);
		// 设置建立连接超时时间
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT);
		// 设置读数据超时时间
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(READ_DATA_TIMEOUT);
		// 设置编码
		postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, CONTENT_CHARSET);
		// 使用系统提供的默认的恢复策略
		postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

		try {
			try {
				int statusCode = httpClient.executeMethod(postMethod);
				if (statusCode != HttpStatus.SC_OK) {
					throw new ApiException("Request [" + url + "] failed:" + postMethod.getStatusLine());
				}
				// 读取内容
				byte[] responseBody = postMethod.getResponseBody();
				return new String(responseBody, CONTENT_CHARSET);
			} finally {
				// 释放链接
				postMethod.releaseConnection();
			}
		} catch (HttpException e) {
			// 发生致命的异常,可能是协议不对或者返回的内容有问题
			throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
		} catch (IOException e) {
			// 发生网络异常
			throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
		}
	}
	
	/**
	 * 发送Get请求
	 * 
	 * @param url
	 *            请求URL地址
	 * @param params
	 *            请求参数
	 * @param protocol
	 *            请求协议 "http" / "https"
	 * @return 服务器响应的请求结果
	 */
	public static String get(String url, HashMap<String, String> params,
			HashMap<String, String> cookies, String protocol) throws ApiException {
//		if (protocol.equalsIgnoreCase("https")) {
//			Protocol httpsProtocol = new Protocol("https", new SecureProtocolSocketFactoryImpl(), 443);
//			Protocol.registerProtocol("https", httpsProtocol);
//		}

		HttpClient httpClient = new HttpClient();
		GetMethod getMethod = new GetMethod(url);
//		PostMethod postMethod = new PostMethod(url);

		// 设置请求参数
		if (params != null && !params.isEmpty()) {
			NameValuePair[] data = new NameValuePair[params.size()];
			Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
			int i = 0;
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				data[i] = new NameValuePair(entry.getKey(), entry.getValue());
				++i;
			}
			getMethod.setQueryString(data);
		}

		// 设置cookie
		if (cookies != null && !cookies.isEmpty()) {
			Iterator<Entry<String, String>> iterator = cookies.entrySet().iterator();
			StringBuilder buffer = new StringBuilder(128);
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				buffer.append(entry.getKey()).append("=").append(entry.getValue()).append("; ");
			}
			// 设置cookie策略
			getMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
			// 设置cookie内容
			getMethod.setRequestHeader("Cookie", buffer.toString());
		}

		// 设置User-Agent
		getMethod.setRequestHeader("User-Agent", USER_AGENT);
		// 设置建立连接超时时间
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT);
		// 设置读数据超时时间
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(READ_DATA_TIMEOUT);
		// 设置编码
		getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, CONTENT_CHARSET);
		// 使用系统提供的默认的恢复策略
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

		try {
			try {
				int statusCode = httpClient.executeMethod(getMethod);
				if (statusCode != HttpStatus.SC_OK) {
					throw new ApiException("Request [" + url + "] failed:" + getMethod.getStatusLine());
				}
				// 读取内容
				byte[] responseBody = getMethod.getResponseBody();
				return new String(responseBody, CONTENT_CHARSET);
			} finally {
				// 释放链接
				getMethod.releaseConnection();
			}
		} catch (HttpException e) {
			// 发生致命的异常,可能是协议不对或者返回的内容有问题
			throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
		} catch (IOException e) {
			// 发生网络异常
			throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
		}
	}

	/**
	 * POST提交JSON格式的内容
	 */
	private static String postJson(String url, Map<String, Object> params,
			HashMap<String, String> cookies, String protocol) throws ApiException {
//		if (protocol.equalsIgnoreCase("https")) {
//			Protocol httpsProtocol = new Protocol("https", new SecureProtocolSocketFactoryImpl(), 443);
//			Protocol.registerProtocol("https", httpsProtocol);
//		}

		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(url);

		// 设置请求参数
		if (params != null && !params.isEmpty()) {
			ObjectMapper mapper = new ObjectMapper();
			try {
				String requestBody = mapper.writeValueAsString(params);
				StringRequestEntity requestEntity = new StringRequestEntity(
						requestBody, "text/json", CONTENT_CHARSET);
				postMethod.setRequestEntity(requestEntity);
			} catch (JsonProcessingException e) {
				throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
			} catch (UnsupportedEncodingException e) {
				throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
			}
		}

		// 设置cookie
		if (cookies != null && !cookies.isEmpty()) {
			Iterator<Entry<String, String>> iterator = cookies.entrySet().iterator();
			StringBuilder buffer = new StringBuilder(128);
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				buffer.append(entry.getKey()).append("=").append(entry.getValue()).append("; ");
			}
			// 设置cookie策略
			postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
			// 设置cookie内容
			postMethod.setRequestHeader("Cookie", buffer.toString());
		}

		// 设置User-Agent
		postMethod.setRequestHeader("User-Agent", USER_AGENT);
		// 设置建立连接超时时间
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT);
		// 设置读数据超时时间
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(READ_DATA_TIMEOUT);
		// 设置编码
		postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, CONTENT_CHARSET);
		// 使用系统提供的默认的恢复策略
		postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

		try {
			try {
				int statusCode = httpClient.executeMethod(postMethod);
				if (statusCode != HttpStatus.SC_OK) {
					throw new ApiException("Request [" + url + "] failed:" + postMethod.getStatusLine());
				}
				// 读取内容
				byte[] responseBody = postMethod.getResponseBody();
				return new String(responseBody, CONTENT_CHARSET);
			} finally {
				// 释放链接
				postMethod.releaseConnection();
			}
		} catch (HttpException e) {
			// 发生致命的异常,可能是协议不对或者返回的内容有问题
			throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
		} catch (IOException e) {
			// 发生网络异常
			throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
		}
	}

	/**
	 * 发送POST请求(上传文件)
	 * 
	 * @param url
	 *            请求URL地址
	 * @param params
	 *            请求参数
	 * @param protocol
	 *            请求协议 "http" / "https"
	 * @param fp
	 *            上传的文件
	 * @return 服务器响应的请求结果
	 */
	private static String postWithFile(String url,
			HashMap<String, String> params, HashMap<String, String> cookies,
			FilePart fp, String protocol) throws ApiException {
//		if (protocol.equalsIgnoreCase("https")) {
//			Protocol httpsProtocol = new Protocol("https", new SecureProtocolSocketFactoryImpl(), 443);
//			Protocol.registerProtocol("https", httpsProtocol);
//		}

		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(url);

		List<Part> parts = new ArrayList<Part>();
		parts.add(fp);

		// 设置请求参数
		if (params != null && !params.isEmpty()) {
			Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				// 设置参数为UTF-8编码集,解决中文乱码问题,并且将参数加到post中
				parts.add(new StringPart(entry.getKey(), entry.getValue(), CONTENT_CHARSET));
			}
		}
		MultipartRequestEntity requestEntity = new MultipartRequestEntity(
				(Part[]) parts.toArray(), postMethod.getParams());
		postMethod.setRequestEntity(requestEntity);

		// 设置cookie
		if (cookies != null && !cookies.isEmpty()) {
			Iterator<Entry<String, String>> iterator = cookies.entrySet().iterator();
			StringBuilder buffer = new StringBuilder(128);
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				buffer.append(entry.getKey()).append("=").append(entry.getValue()).append("; ");
			}
			// 设置cookie策略
			postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
			// 设置cookie内容
			postMethod.setRequestHeader("Cookie", buffer.toString());
		}

		// 设置User-Agent
		postMethod.setRequestHeader("User-Agent", USER_AGENT);
		// 设置建立连接超时时间
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT);
		// 设置读数据超时时间
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(READ_DATA_TIMEOUT);
		// 使用系统提供的默认的恢复策略
		postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

		// 发送请求
		try {
			try {
				postMethod.getParams().setContentCharset("UTF-8");
				int statusCode = httpClient.executeMethod(postMethod);
				if (statusCode != HttpStatus.SC_OK) {
					throw new ApiException("Request [" + url + "] failed:" + postMethod.getStatusLine());
				}
				// 读取内容
				byte[] responseBody = postMethod.getResponseBody();
				return new String(responseBody, CONTENT_CHARSET);
			} finally {
				// 释放链接
				postMethod.releaseConnection();
			}
		} catch (HttpException e) {
			// 发生致命的异常,可能是协议不对或者返回的内容有问题
			throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
		} catch (IOException e) {
			// 发生网络异常
			throw new ApiException("Request [" + url + "] failed:" + e.getMessage());
		}
	}
}