HttpClientUtil 工具类(http请求工具类)

package com.kk.utils.http;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HttpClient调用工具类
 * httpclient
 */
public class HttpClientUtil {
	private static final Log logger = LogFactory.getLog("httpClient");

	/**
	 * 发送GET请求
	 * 
	 * @param uri
	 * @return
	 */
	public static String sendGet(String uri) {
		String responseBody = null;
		HttpClient httpClient = new DefaultHttpClient();
		// 设置超时时间
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				10000);
		try {
			// URLEncoder.encode(uri, "utf-8");
			HttpGet httpGet = new HttpGet(uri);
			logger.info("executing request " + httpGet.getURI());
			// Create a response handler
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			responseBody = httpClient.execute(httpGet, responseHandler);
			logger.info(responseBody);
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return responseBody;
	}

	/**
	 * 发送GET请求,返回字节数组
	 * 
	 * @param uri
	 * @return
	 */
	public static byte[] sendGetReturnByte(String uri) {
		byte[] output = null;
		HttpClient httpClient = new DefaultHttpClient();
		// 设置超时时间
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				10000);
		try {
			HttpGet httpGet = new HttpGet(uri);
			HttpResponse responseBody = httpClient.execute(httpGet);
			HttpEntity entry = responseBody.getEntity();
			InputStream input = entry.getContent();
			output = IOUtils.toByteArray(input);
			input.close();
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage(), e);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return output;
	}

	/**
	 * 发送POST请求
	 * 
	 * @param uri
	 * @param paramMap
	 *            请求参数
	 * @return
	 */
	public static String sendPost(String uri, Map<String, String> paramMap) {
		return sendPost(uri, paramMap, null);
	}

	/**
	 * 发送POST请求
	 * 
	 * @param uri
	 * @param paramMap
	 *            请求参数
	 * @param charset
	 *            参数编码
	 * @return
	 */
	public static String sendPost(String uri, Map<String, String> paramMap,
			String charset) {
		String responseBody = null;
		HttpClient httpClient = new DefaultHttpClient();
		// 设置超时时间
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
		try {
			HttpPost httpPost = new HttpPost(uri);
			logger.info("executing request " + httpPost.getURI());
			if (paramMap != null) {
				List<NameValuePair> nvps = new ArrayList<NameValuePair>(paramMap.size());
				for (Map.Entry<String, String> entry : paramMap.entrySet()) {
					NameValuePair nvp = new BasicNameValuePair(entry.getKey(), entry.getValue());
					nvps.add(nvp);
				}
				if (charset != null) {
					httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));
				} else {
					httpPost.setEntity(new UrlEncodedFormEntity(nvps));
				}
			}
			// Create a response handler
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			responseBody = httpClient.execute(httpPost, responseHandler);
			logger.info("----------------------------------------");
			logger.info(responseBody);
			logger.info("----------------------------------------");
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return responseBody;

	}

	/**
	 * Extends the post data
	 */
	public static String sendPostRequest(String _url, String data) {

		try {
			// Send the request
			URL url = new URL(_url);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestProperty("content-type", "application/json");
			OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

			// write parameters
			if (data != null) {
				writer.write(data);
			}
			writer.flush();

			// Get the response
			StringBuffer answer = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				answer.append(line);
			}
			writer.close();
			reader.close();

			// Output the response
			return answer.toString();

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
		return null;
	}

	/**
	 * 注意contentType
	 *
	 * 如果中文乱码 需要再进行转码
	 * <p/>
	 * resultStr = new String(resultStr.getBytes("ISO-8859-1"), "utf-8");
	 */
	public static String postData2(String url, String data) {
		HttpClient client = new DefaultHttpClient();
		// 设置超时时间
		client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);

		String responseBody = null;
		try {
			HttpPost httpPost = new HttpPost(url);

//			httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
			httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
			httpPost.setHeader(HTTP.CONTENT_ENCODING, "utf-8");

			StringEntity payload = new StringEntity(data, "UTF-8");
			httpPost.setEntity(payload);

			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			responseBody = client.execute(httpPost, responseHandler);
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			client.getConnectionManager().shutdown();
		}
		return responseBody;
	}

	/**
	 * 可以处理中文乱码,
	 */
	public static String postData(String url, String data) {
		StringBuilder sb = new StringBuilder();
		HttpPost httpPost = new HttpPost(url);
		HttpEntity entity = null;

//		httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
		httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
		try {

			HttpClient client = new DefaultHttpClient();
			StringEntity payload = new StringEntity(data, "UTF-8");
			httpPost.setEntity(payload);
			HttpResponse response = client.execute(httpPost);
			entity = response.getEntity();
			String text;
			if (entity != null) {
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
				while ((text = bufferedReader.readLine()) != null) {
					sb.append(text);
				}

			}
		} catch (Exception e) {
			logger.error("与[" + url + "]通信过程中发生异常,堆栈信息如下", e.getCause());
		} finally {
			try {
				EntityUtils.consume(entity);
			} catch (IOException ex) {
				ex.printStackTrace();
				logger.error("net io exception");
			}
		}
		return sb.toString();
	}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清汉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值