HttpClient的使用

HttpClient工具类

postData方法传三个参数:url地址,Map<String,String>参数放到map中,编码方式

package com.hc360.oauth.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;



public class HttpRequestUtil {
	
	public static String addUrl(String head, String tail) {
		if (head.endsWith("/")) {
			if (tail.startsWith("/")) {
				return head.substring(0, head.length() - 1) + tail;
			} else {
				return head + tail;
			}
		} else {
			if (tail.startsWith("/")) {
				return head + tail;
			} else {
				return head + "/" + tail;
			}
		}
	}

	public synchronized static String postData(String url, Map<String, String> params, String codePage) throws Exception {

		final HttpClient httpClient = new HttpClient();
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10 * 1000);
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(10 * 1000);

		final PostMethod method = new PostMethod(url);
		if (params != null) {
			method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, codePage);
			method.setRequestBody(assembleRequestParams(params));
		}
		String result = "";
		try {
			httpClient.executeMethod(method);
			result = new String(method.getResponseBody(), codePage);
		} catch (final Exception e) {
			throw e;
		} finally {
			method.releaseConnection();
		}
		return result;
	}

	public synchronized static String postData(String url, String codePage) throws Exception {
		final HttpClient httpClient = new HttpClient();
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10 * 1000);
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(10 * 1000);

		final GetMethod method = new GetMethod(url);
		String result = "";
		try {
			httpClient.executeMethod(method);
			result = new String(method.getResponseBody(), codePage);
		} catch (final Exception e) {
			throw e;
		} finally {
			method.releaseConnection();
		}
		return result;
	}

	/**
	 * 组装http请求参数
	 * 
	 * @param params
	 * @param menthod
	 * @return
	 */
	private synchronized static NameValuePair[] assembleRequestParams(Map<String, String> data) {
		final List<NameValuePair> nameValueList = new ArrayList<NameValuePair>();

		Iterator<Map.Entry<String, String>> it = data.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
			nameValueList.add(new NameValuePair((String) entry.getKey(), (String) entry.getValue()));
		}

		return nameValueList.toArray(new NameValuePair[nameValueList.size()]);
	}
	public static void main(String[] args) {
//        String posturl = "https://sso.hc360.com/ssologin";
////		String LoginID = request.getParameter("LoginID");
////		String Passwd = request.getParameter("Passwd");
//		HashMap<String,String> map = new HashMap<String,String>();
//		map.put("LoginID","jinjiangjiayi" );
//		map.put("Passwd","1q2w3e4r5t" );
//		map.put("LoginType","json" );
////		if(StringUtils.isNotBlank(LoginID)){
//			try {
//				String ret = HttpRequestUtil.postData(posturl, map, "gbk");
//				if("null({success:\"yes\"})".equals(ret)){
//					System.out.println("++++");
//				}
//				System.out.println(ret);
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
////		}
		
		String postUrlforUser = "http://my.b2b.hc360.com/my/turbine/template/firstview,corinfo4chat.html";
		HashMap<String,String> uMap = new HashMap<String, String>();
		uMap.put("username", "jinjiangjiayi");
		try {
			String userStr = HttpRequestUtil.postData(postUrlforUser, uMap, "gbk");
//			System.out.println(userStr);
//			System.out.println("============");
//			String[] str = userStr.split("\\n");
//			for (int i = 0; i < str.length; i++) {
//				System.out.println(str[i]);
//			}
//			SSOUser user = ToSSOUserUtil.getSSOUser(userStr);
//			System.out.println(user.getName());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

  

posted @ 2015-01-29 09:38  刘尊礼  阅读(279)  评论(0)    收藏  举报