Java http调用接口

Java http调用接口

    • MyX509TrustManager(信任管理器)
    • HttpUtil(调用接口)

MyX509TrustManager(信任管理器)

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

/**
 * 类名: MyX509TrustManager 
* 描述: 信任管理器
* 开发人员: fj
* 创建时间: 2018-6-12
* 发布版本:V1.0
*/
public class MyX509TrustManager implements X509TrustManager { // 检查客户端证书 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // 不检查 } // 检查服务器端证书 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // 不检查 } // 返回受信任的X509证书数组 public X509Certificate[] getAcceptedIssuers() { return null; } }

HttpUtil(调用接口)

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 网络请求 调用接口
 */
public class HttpUtil {
	/**
	 * GET请求方式
	 */
	public static final String GET = "GET";
	/**
	 * POST请求方式
	 */
	public static final String POST = "POST";
	/**
	 * 编码格式:UTF-8
	 */
	private static final String UTF_8 = "UTF-8";

	/**
	 * 发起POST请求并获取结果,返回结果为JSON格式对象
	 * 
	 * @param urlStr
	 *            请求地址 String
	 * @param post
	 *            提交的数据 String
	 * @return JSON 响应结果 JSON格式对象
	 */
	public static JSONObject requestToJson(String urlStr, String post) {
		return JSON.parseObject(request(urlStr, HttpUtil.POST, post));
	}

	/**
	 * 发起GET请求并获取结果,返回结果为JSON格式对象
	 * 
	 * @param urlStr
	 *            请求地址 String
	 * @return JSON 响应结果 JSON格式对象
	 */
	public static JSONObject requestToJson(String urlStr) {
		return JSON.parseObject(request(urlStr, HttpUtil.GET, ""));
	}

	/**
	 * 发起POST请求并获取结果,返回结果为Map对象
	 * 
	 * @param urlStr
	 *            请求地址 String
	 * @param post
	 *            提交的数据 String
	 * @return Map<String, String> 响应结果 (xml转为)Map对象
	 */
	public static Map<String, String> requestToMap(String urlStr, String post) {
		try {
			return xml2Map(request(urlStr, HttpUtil.POST, post));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 发起GET请求并获取结果,返回结果为Map对象
	 * 
	 * @param urlStr
	 *            请求地址 String
	 * @return Map<String, String> 响应结果 (xml转为)Map对象
	 */
	public static Map<String, String> requestToMap(String urlStr) {
		try {
			return xml2Map(request(urlStr, HttpUtil.GET, null));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址 String
	 * @param requestMethod
	 *            请求方式(GET/POST) String
	 * @param outputStr
	 *            提交的数据 String
	 * @return String 响应结果
	 */
	public static String request(String urlStr, String method, String post) {
		String result = null;
		try {
			// 创建SSLContext对象,并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(null, urlStr, new sun.net.www.protocol.https.Handler());
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式(GET/POST)
			httpUrlConn.setRequestMethod(method);
			if (GET.equalsIgnoreCase(method)) {
				httpUrlConn.connect();
			}
			// 当有数据需要提交时
			if (null != post) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式,防止中文乱码
				outputStream.write(post.getBytes(UTF_8));
				outputStream.close();
			}
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			result = is2Str(inputStream);
			httpUrlConn.disconnect();
		} catch (ConnectException ce) {
			ce.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 解析输入流
	 * 
	 * @param inputStream
	 *            输入流
	 * @return 解析结果成字符串
	 */
	public static String is2Str(InputStream inputStream) {
		StringBuffer buffer = new StringBuffer();
		InputStreamReader inputStreamReader = null;
		BufferedReader bufferedReader = null;
		try {
			inputStreamReader = new InputStreamReader(inputStream, UTF_8);
			bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 释放资源
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
				if (inputStreamReader != null) {
					inputStreamReader.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		inputStream = null;
		return buffer.toString();
	}
	
	/**
	 * XML格式字符串转换为Map
	 *
	 * @param strXML
	 *            XML 字符串
	 * @return Map<String, String> 数据转换后的Map
	 * @throws Exception
	 */
	public static Map<String, String> xml2Map(String strXML) {
		Map<String, String> data = null;
		InputStream is = new ByteArrayInputStream(strXML.getBytes());
		data = is2Map(is);
		return data;
	}

	/**
	 * 解析输入流
	 * 
	 * @param inputStream
	 *            输入流
	 * @return 解析结果存储在Map中
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> is2Map(InputStream inputStream) {
		// 将解析结果存储在HashMap中
		Map<String, String> map = new HashMap<String, String>();
		// 读取输入流
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(inputStream);
			// 得到xml根元素
			Element root = document.getRootElement();
			// 得到根元素的所有子节点
			List<Element> elementList = root.elements();
			// 遍历所有子节点
			for (Element e : elementList)
				map.put(e.getName(), e.getText());
			// 释放资源
		} catch (DocumentException e) {
			e.printStackTrace();
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		inputStream = null;
		return map;
	}

	private static final String PREFIX_XML = "";

	private static final String SUFFIX_XML = "";

	private static final String PREFIX_CDATA = ";

	private static final String SUFFIX_CDATA = "]]>";

	/**
	 * Map转换为XML格式字符串
	 * 
	 * @param map
	 *            map源
	 * @param isAddCDATA
	 *            是否含有CDATA
	 * @return
	 */
	public static String map2Xml(Map<String, String> parm, boolean isAddCDATA) {
		StringBuffer strbuff = new StringBuffer(PREFIX_XML);
		if (null != parm) {
			for (Entry<String, String> entry : parm.entrySet()) {
				strbuff.append("<").append(entry.getKey()).append(">");
				if (isAddCDATA) {
					strbuff.append(PREFIX_CDATA);
					if (null != entry.getValue()) {
						strbuff.append(entry.getValue());
					}
					strbuff.append(SUFFIX_CDATA);
				} else {
					if (null != entry.getValue()) {
						strbuff.append(entry.getValue());
					}
				}
				strbuff.append(").append(entry.getKey()).append(">");
			}
		}
		return strbuff.append(SUFFIX_XML).toString();
	}
}

你可能感兴趣的:(后端)