java代码使用https访问接口

<pre name="code" class="java">/**
 * Test.java
 * cn.ffcs.interf.common.util
 *
 * Function: TODO 
 *
 *   ver     date      		author
 * ──────────────────────────────────
 *   		 14-六月-14 		caigch
 *
 * Copyright (c) 2014, TNT All Rights Reserved.
 */

package cn.ffcs.portal.library.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

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

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
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.lang.StringUtils;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
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;

/**
 * ClassName:HttpsUtil
 * 
 * 模拟https请求
 * 
 * @author pengyh
 * @version 1.0
 * @since v1.0
 * @Date 14-六月-14 上午 11:11
 */
public class HttpsUtil {
	
	private static final Logger LOG = LoggerFactory.getLogger(HttpsUtil.class);

	public static DefaultHttpClient getHttpsClient() {
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {

				@Override
				public void checkClientTrusted(
						java.security.cert.X509Certificate[] chain,
						String authType)
						throws java.security.cert.CertificateException {
				}

				@Override
				public void checkServerTrusted(
						java.security.cert.X509Certificate[] chain,
						String authType)
						throws java.security.cert.CertificateException {
				}

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

			};
			DefaultHttpClient client = new DefaultHttpClient();
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(ctx);

			ClientConnectionManager ccm = client.getConnectionManager();
			SchemeRegistry sr = ccm.getSchemeRegistry();
			// 设置要使用的端口,默认是443
			sr.register(new Scheme("https", 443, ssf));
			return client;
		} catch (Exception ex) {
			LOG.error("", ex);
			return null;
		}
	}

	/**
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @author asflex
	 * @throws UnsupportedEncodingException
	 * @date 2014-3-28下午7:24:02
	 * @modify 2014-3-28下午7:24:02
	 */
	@SuppressWarnings("unchecked")
	public static String post(String url, Map<String, String> params)
			throws UnsupportedEncodingException {
		DefaultHttpClient httpClient = getHttpsClient();
		HttpPost post = new HttpPost(url);
		List data = null;
		if (params != null) {
			data = new ArrayList(params.size());
			for (Map.Entry entry : params.entrySet()) {
				data.add(new BasicNameValuePair((String) entry.getKey(),
						(String) entry.getValue()));
			}
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(data,
					"UTF-8");
			post.setEntity(formEntity);
		}
		LOG.info("http post---{}", getUrlRequestInfo(url, params));
		HttpResponse response;
		try {
			response = httpClient.execute(post);
			String result = EntityUtils.toString(response.getEntity());
			return result;
		} catch (ClientProtocolException e) {
			LOG.error("", e);
		} catch (IOException e) {
			LOG.error("", e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return null;
	}

	/**
	 * 上传图片文件
	 * @param url   请求url
	 * @param savedDir  保存文件
	 * @param saveFileName  文件名称
	 * @return  status==0  成功  status==-1  失败  msg失败原因  data成功返回的数据
	 */
	public static JSONObject postImg(String url, File savedDir,
			String saveFileName) {

		HttpClient client = new HttpClient();
		// 返回结果集
		JSONObject resJson = new JSONObject();

		try {
			// 判断白村文件存不存在
			if (!savedDir.exists()) {
				resJson.put("status", "-1");
				resJson.put("msg", "保存文件不存在");
				return resJson;
			}
			PostMethod postMethod = new PostMethod(url);

			// FilePart:用来上传文件的类
			FilePart filePart = new FilePart("img", new File(savedDir,
					saveFileName));
			Part[] parts = { filePart };
			// 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
			MultipartRequestEntity mre = new MultipartRequestEntity(parts,
					postMethod.getParams());
			postMethod.setRequestEntity(mre);

			// 执行请求,返回状态码
			int status = client.executeMethod(postMethod);

			if (status == HttpStatus.SC_OK) {
				LOG.info("上传到易信服务器请求成功,返回信息:"
						+ postMethod.getResponseBodyAsString());
				String result = postMethod.getResponseBodyAsString();
				if (result != null && !result.trim().equals("")) {
					// 解析返回信息
					resJson = JSONObject.parseObject(result);
					String code = resJson.get("errcode").toString(); // 对方接口请求返回结果:0成功
																		// 其余失败
					if (code != null && code.trim().equals("0")) {
						LOG.info("上传成功。返回信息:"
								+ postMethod.getResponseBodyAsString());
						resJson.put("status", "0");
						return resJson;
					} else {
						LOG.info("上传失败。返回信息:" + resJson.get("msg").toString());
						resJson.put("status", "-1");
						return resJson;
					}
				}
			} else {
				LOG.info("请求易信接口上传图片,请求失败。");
				resJson.put("status", "-1");
				resJson.put("msg", "上传图片,请求失败。");
				return resJson;
			}
		} catch (Exception e) {
			resJson.put("status", "-1");
			resJson.put("msg", "系统异常");
			return resJson;
		}
		return null;
	}

	public static String get(String url) throws UnsupportedEncodingException {
		DefaultHttpClient httpClient = getHttpsClient();
		HttpGet get = new HttpGet(url);
		// LOG.info("http post---{}", getUrlRequestInfo(url, params));
		HttpResponse response;
		try {
			response = httpClient.execute(get);
			String result = EntityUtils.toString(response.getEntity());
			return result;
		} catch (ClientProtocolException e) {
			LOG.error("", e);
		} catch (IOException e) {
			LOG.error("", e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return null;
	}

	/**
	 * 生成post请求时的记录
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @author asflex
	 * @date 2014-3-28下午7:23:33
	 * @modify 2014-3-28下午7:23:33
	 */
	public static String getUrlRequestInfo(String url,
			Map<String, String> params) {

		StringBuilder paramStr = new StringBuilder();
		if (!params.isEmpty()) {
			@SuppressWarnings("unused")
			Iterator<Entry<String, String>> iterator = params.entrySet()
					.iterator();
			// Joiner.on("&").appendTo(paramStr, iterator);
		}
		return String
				.format("curl -d '%s' '%s'", StringUtils.trimToEmpty(paramStr
						.toString()), StringUtils.trimToEmpty(url));
	}

	/**
	 * 参数转换
	 * 
	 * @param params
	 * @return
	 * @author asflex
	 * @date 2014-3-28下午7:23:05
	 * @modify 2014-3-28下午7:23:05
	 */
	public static HttpEntity map2UrlEncodedFormEntity(Map<String, String> params) {
		if (!params.isEmpty()) {
			Iterator<Entry<String, String>> iterator = params.entrySet()
					.iterator();
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				nvps.add(new BasicNameValuePair(StringUtils.trimToEmpty(entry
						.getKey()), StringUtils.trimToEmpty(entry.getValue())));
			}
			try {
				return new UrlEncodedFormEntity(nvps);
			} catch (UnsupportedEncodingException e) {
				LOG.error("", e);
			}
		}
		return null;
	}

	// public static void main(String[] args) {
	// Map<String, String> params = new HashMap<String, String>();
	// params.put("code", "C0001");
	// params.put("openid", "b29f7943b2c9a504c3061cd18d77b7a0");
	// params.put("content", "你好");
	// System.out.println(getUrlRequestInfo("", params));
	//
	// try {
	// System.out.println(post(
	// "https://campus.yixin.im/api/private/msg/simpleSend.do",
	// params));
	// System.out
	// .println(get("https://campus.yixin.im/api/private/user/mInfo.do?code=C0001&mobile=18950426152"));
	//
	// System.out.println(get("http://campus.yixin.im/api/private/queryNameCodeList.do"));
	// } catch (UnsupportedEncodingException e) {
	//
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	//
	// }
	// }
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值