java HttpClient在客户端处理service服务数据解决方案一例

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.util.Date;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.log4j.Logger;

import com.tjsoft.util.StringUtil;

public class ClientUtil {
	private static Logger log = Logger.getLogger(ClientUtil.class);

	/**
	 * 登录 获取token
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public static String login() throws Exception {
		log.info("info:"+new Date().toLocaleString()+"开始执行" + ClientUtil.class + "类 login()方法.");
		String url = ServiceUrlUtil.LOGIN;
		String json = "{\"loginId\":\"" + ServiceUrlUtil.SERVICE_LOGINID.trim()
				+ "\"," + "\"password\":\""
				+ ServiceUrlUtil.SERVICE_PASSWORD.trim() + "\","
				+ "\"auth_key\":\"" + ServiceUrlUtil.SERVICE_AUTHKEY.trim()
				+ "\"" + "}";
		//System.out.println("json----------------->"+json);
		String result = requestForStringUsePost(url, json);
		//System.out.println("result----------------->"+result);
		String eCode = JSONObject.fromObject(result).getString("eCode");
		String eMsg = JSONObject.fromObject(result).getString("eMsg");
		String token = JSONObject.fromObject(result).getString("token");
		//System.out.println("eCode----->"+eCode+",eMsg---------->"+eMsg+",token------------->"+token);
		log.info("info:"+new Date().toLocaleString()+"执行" + ClientUtil.class + "类 login()方法:" + eCode + "-"
				+ eMsg + ",返回值:" + token);
		return token;
	}

	/**
	 * 注销登录
	 * 
	 * @param access_token
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public static String logout(String token) throws Exception {
		log.info("info:"+new Date().toLocaleString()+"开始执行" + ClientUtil.class + "类 login()方法.");
		String url = ServiceUrlUtil.LOGOUT+"?token="+token;
		String result = ClientUtil.requestForStringUseGet(url);
		String eCode = JSONObject.fromObject(result).get("eCode").toString();
		String eMsg = JSONObject.fromObject(result).get("eMsg").toString();
		//System.out.println("eCode----->"+eCode+",eMsg---------->"+eMsg);
		log.info("info:"+new Date().toLocaleString()+"执行" + ClientUtil.class + "类 logout()方法:" + eCode + "-"
				+ eMsg + ".");
		return result;
	}

	/**
	 * 这里需要传入机构ID 查询机构下的窗口的时候 需要传入该机构编号 然后返回accessToken
	 * 
	 * @throws Exception
	 */
	/*
	 * public static String getSessionOrgCode(String orgCode) throws Exception {
	 * String url = "http://sxsl.sz.gov.cn/sxgl/c/api.pmi/login"; String json = "
	 * {\"key\":\"" + ServiceUrlUtil.APP_KEY + "\",\"secret\":\"" +
	 * ServiceUrlUtil.APP_SECRET + "\",\"loginname\":\"" +
	 * ServiceUrlUtil.ACCOUNT + "\", " + " \"pwd\":\"" + ServiceUrlUtil.PASSWORD +
	 * "\",\"dept\":\"" + orgCode + "\"}"; String result =
	 * ClientUtil.requestForStringUsePost(url, json); Object data =
	 * JSONObject.fromObject(result).get("data"); String access_token ="";
	 * if(data!=null){ access_token =
	 * JSONObject.fromObject(data).getString("access_token"); } return
	 * access_token; }
	 */

	/**
	 * 调用http请求,返回string结果数据
	 * 
	 * @param req
	 *            json格式请求参数
	 * @param fi
	 * @return
	 */
	public static String requestForStringUseGet(String url) throws Exception {
		String returnStr = "";
		HttpResponse httpResponse = null;
		DefaultHttpClient httpClient = null;
		httpClient = new DefaultHttpClient();// http客户端
		enableSSL(httpClient);

		httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
				false);
		// 连接超时
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(ServiceUrlUtil.TIME_OUT.trim()));

		// 请求超时
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				30000);
		httpClient.getParams().setParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

		// 请求地址
		HttpGet httpget = new HttpGet(url);

		@SuppressWarnings("unused")
		Date sDate = new Date();
		httpResponse = httpClient.execute(httpget);
		// 请求结果处理
		HttpEntity entity = httpResponse.getEntity();

		if (entity != null) {
			InputStream content = entity.getContent();
			returnStr = convertStreamToString(content);
		}
		// 释放连接
		if (httpClient != null) {
			httpClient.getConnectionManager().shutdown();
			httpClient = null;
		}
		return returnStr;

	}

	/**
	 * 调用http请求,返回string结果数据
	 * 
	 * @param req
	 *            json格式请求参数
	 * @param fi
	 * @return
	 */
	public static String requestForStringUsePost(String url, String json)
			throws Exception {
		String returnStr = "";
		HttpResponse httpResponse = null;
		DefaultHttpClient httpClient = null;

		@SuppressWarnings("unused")
		Date sDate = new Date();

		// 请求参数
		httpClient = new DefaultHttpClient();// http客户端
		enableSSL(httpClient);
		httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
				false);
		// 连接超时
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(ServiceUrlUtil.TIME_OUT.trim()));

		// 请求超时
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				30000);
		httpClient.getParams().setParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		// 请求地址
		HttpPost httppost = new HttpPost(url);
		if (StringUtil.isNotBlank(json)) {
			StringEntity stringEntity = new StringEntity(json, "utf-8");
			httppost.setEntity(stringEntity);
		} else {
			StringEntity stringEntity = new StringEntity("{}", "utf-8");
			httppost.setEntity(stringEntity);
		}
		httppost.setHeader("Content-type", "application/json");
		httpResponse = httpClient.execute(httppost);
		// 请求结果处理
		HttpEntity entity = httpResponse.getEntity();

		if (entity != null) {
			InputStream content = entity.getContent();
			returnStr = convertStreamToString(content);
		}

		// 释放连接
		if (httpClient != null) {
			httpClient.getConnectionManager().shutdown();
			httpClient = null;
		}
		return returnStr;
	}

	/**
	 * 将流转换为字符串
	 * 
	 * @param is
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String convertStreamToString(InputStream is)
			throws UnsupportedEncodingException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is,
				"utf-8"));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	@SuppressWarnings("deprecation")
	private static void enableSSL(DefaultHttpClient httpclient) {
		// 调用ssl
		try {
			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
			SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
			sf
					.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme https = new Scheme("https", sf, 443);
			httpclient.getConnectionManager().getSchemeRegistry().register(
					https);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 重写验证方法,取消检测ssl
	 */
	private static TrustManager truseAllManager = new X509TrustManager() {

		public void checkClientTrusted(
				java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {

		}

		public void checkServerTrusted(
				java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {

		}

		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}

	};

	/**
	 * 测试
	 * 
	 * @Description: TODO
	 * @param args
	 *            void
	 * @throws Exception
	 */
	@SuppressWarnings("static-access")
	public static void main(String[] args) throws Exception {
		ClientUtil util = new ClientUtil();
		String token = util.login();
		System.out.println(token);
		//String token = "VCRt853rOjH_aHh-1-fLLOQdW-wcu-pyLh2LT3jjP2cJ3SCF1qDp!-366310036!1384824151531";
		util.logout(token);
	}

}

你可能感兴趣的:(java HttpClient在客户端处理service服务数据解决方案一例)