HttpClient接口调用

HttpClient.java

package com.enuo.mall.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

public class HttpClient {

	private static Logger logger = LoggerFactory.getLogger(HttpClient.class);

	public static String doGet(String httpurl) {
		HttpURLConnection connection = null;
		InputStream is = null;
		BufferedReader br = null;
		String result = null;// 返回结果字符串
		try {
			// 创建远程url连接对象
			URL url = new URL(httpurl);
			// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
			connection = (HttpURLConnection) url.openConnection();
			// 设置连接方式:get
			connection.setRequestMethod("GET");
			// 设置连接主机服务器的超时时间:15000毫秒
			connection.setConnectTimeout(15000);
			// 设置读取远程返回的数据时间:60000毫秒
			connection.setReadTimeout(60000);
			// 发送请求
			connection.connect();
			logger.debug("---------接口地址:" + url);
			// 通过connection连接,获取输入流
			if (connection.getResponseCode() == 200) {
				is = connection.getInputStream();
				// 封装输入流is,并指定字符集
				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				// 存放数据
				StringBuffer sbf = new StringBuffer();
				String temp = null;
				while ((temp = br.readLine()) != null) {
					sbf.append(temp);
					sbf.append("\r\n");
				}
				result = sbf.toString();
				logger.debug("应答报文----------" + result.toString());
			} else {
				logger.debug("远程服务器异常,【错误码:" + connection.getResponseCode() + "】");
				throw new RuntimeException("远程服务器异常,【错误码:" + connection.getResponseCode() + "】,应答报文----------" + connection.getResponseCode());
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			connection.disconnect();// 关闭远程连接
		}

		return result;
	}

	public static String doPost(String httpUrl, String param) {

		HttpURLConnection connection = null;
		InputStream is = null;
		OutputStream os = null;
		BufferedReader br = null;
		String result = null;
		try {
			URL url = new URL(httpUrl);
			// 通过远程url连接对象打开连接
			connection = (HttpURLConnection) url.openConnection();
			// 设置连接请求方式
			connection.setRequestMethod("POST");
			// 设置连接主机服务器超时时间:15000毫秒
			connection.setConnectTimeout(15000);
			// 设置读取主机服务器返回数据超时时间:60000毫秒
			connection.setReadTimeout(60000);

			// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
			connection.setDoOutput(true);
			// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
			connection.setDoInput(true);
			// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
			connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
			// 通过连接对象获取一个输出流
			os = connection.getOutputStream();
			// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
			logger.debug("---------接口地址:" + url + ",请求参数:" + param);
			os.write(param.getBytes());
			// 通过连接对象获取一个输入流,向远程读取
			if (connection.getResponseCode() == 200) {

				is = connection.getInputStream();
				// 对输入流对象进行包装:charset根据工作项目组的要求来设置
				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

				StringBuffer sbf = new StringBuffer();
				String temp = null;
				// 循环遍历一行一行读取数据
				while ((temp = br.readLine()) != null) {
					sbf.append(temp);
					sbf.append("\r\n");
				}
				result = sbf.toString();
				logger.debug("应答报文----------" + result.toString());
			} else {
				logger.debug("远程服务器异常,【错误码:" + connection.getResponseCode() + "】");
				throw new RuntimeException("远程服务器异常,【错误码:" + connection.getResponseCode() + "】,应答报文----------" + connection.getResponseCode());
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// 断开与远程地址url的连接
			connection.disconnect();
		}
		return result;
	}	

	public static String postMethod(String httpUrl, Map<String, String> params) throws Exception {
		final org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
		final PostMethod method = new PostMethod(httpUrl);
		method.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
		method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

		if (params != null) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				if (null != entry.getKey() && null != entry.getValue()) {
					method.setParameter(entry.getKey(), entry.getValue());
				}
			}
		}

		logger.debug("---------接口地址:" + CommonUtil.getWholeUrl(httpUrl, params));

		String response = "";
		try {
			int status = httpClient.executeMethod(method);
			if (status >= 300 || status < 200) {
				response = method.getResponseBodyAsString();
				throw new RuntimeException("远程服务器异常,【错误码:" + status + "】,应答报文----------" + response.toString());
			} else {
				response = CommonUtil.parserResponse(method); // 成功
				logger.debug("应答报文----------" + response.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		} finally {

			method.releaseConnection();
		}
		return response;
	}

	public static JSONObject httpRequest(String httpUrl, List<BasicNameValuePair> params) throws Exception {
		final org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
		final PostMethod method = new PostMethod(httpUrl);
		method.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
		method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

		if (params != null) {
			for (BasicNameValuePair entry : params) {
				if (null != entry.getName() && null != entry.getValue()) {
					method.setParameter(entry.getName(), entry.getValue());
				}
			}
		}

		HttpEntity requestEntity = new UrlEncodedFormEntity(params, "UTF-8");

		logger.debug("---------接口地址:" + httpUrl + ",请求参数:"
				+ URLDecoder.decode(EntityUtils.toString(requestEntity), "UTF-8"));

		String response = "";
		try {
			int status = httpClient.executeMethod(method);
			if (status >= 300 || status < 200) {
				response = method.getResponseBodyAsString();
				throw new RuntimeException("远程服务器异常,【错误码:" + status + "】,应答报文----------" + response.toString());
			} else {
				response = CommonUtil.parserResponse(method); // 成功
				logger.debug("应答报文----------" + response.toString());

				if (JsonUtils.isjson(response.toString())) {
					return JSONObject.parseObject(response.toString());
				} else {
					throw new Exception("应答报文----------" + response.toString() + ",不为json字符串");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		} finally {

			method.releaseConnection();
		}
	}
}

CommonUtil.java

package com.enuo.mall.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.methods.PostMethod;

/**
 * 通用工具类,包括了签名工具、url拼装以及httpResponse的解析
 */
public final class CommonUtil {

	/**
	 * 解析http请求的response
	 * 
	 * @param method
	 * @return 请求结果
	 * @throws IOException
	 */
	public static String parserResponse(PostMethod method) throws IOException {
		StringBuffer contentBuffer = new StringBuffer();
		InputStream in = method.getResponseBodyAsStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in, method.getResponseCharSet()));
		String inputLine = null;
		while ((inputLine = reader.readLine()) != null) {
			contentBuffer.append(inputLine);
			contentBuffer.append("\r\n");
		}
		// 去掉结尾的换行符
		contentBuffer.delete(contentBuffer.length() - 2, contentBuffer.length());
		in.close();
		return contentBuffer.toString();
	}

	/**
	 * 获取完整的url
	 * 
	 * @param url
	 *            请求uri
	 * @param params
	 *            请求参数
	 * @return
	 */
	public static String getWholeUrl(String url, Map<String, String> params) {
		if (url == null) {
			return null;
		}
		if (params == null) {
			return url;
		}
		Set<Map.Entry<String, String>> set = params.entrySet();
		if (set.size() <= 0) {
			return url;
		}
		url += "?";
		Iterator<Map.Entry<String, String>> it = set.iterator();
		if (it.hasNext()) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
			String param = entry.getKey() + "=" + entry.getValue();
			url += param;
		}
		while (it.hasNext()) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
			String param = entry.getKey() + "=" + entry.getValue();
			url += "&" + param;
		}
		return url;
	}

	private CommonUtil() {
	}
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值