1. 程式人生 > >https協議的介面的呼叫之get介面!

https協議的介面的呼叫之get介面!

不多說,直接上程式碼。
package com.jxj.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
@Controller
@RequestMapping(value="/search")
public class SearchController {
	
	@ResponseBody
	@RequestMapping(value="/goodsList")
	public String goodsList(String searchKey,String pageIndex,String pageSize){
		
                //將引數編碼
		String encodesearchKey = EncodeAndDecode.encode(searchKey, "utf-8");
		
		String searchUrl="https://xxx/xxx/xxx?g_tk=200330352&pageindex="+pageIndex+"&pagesize="+pageSize+"&key="+encodesearchKey+"&uniquespu=1&storestatus=1&ie=utf-8&text="+encodesearchKey+"&_=15136719724";
		
	
		String resultStr=httpsRequest(searchUrl, "GET", null,null);
		System.out.println("---處理前結果---"+resultStr);
		...此處省略一些我公司業務邏輯...
		return resultStr;
	}
/*
	 * 處理https GET/POST請求
	 * 請求地址、請求方法、引數
	 */
	public static String httpsRequest(String requestUrl,String requestMethod,String outputStr,String cookie){
		StringBuffer buffer=null;
		try{
		//建立SSLContext
		SSLContext sslContext=SSLContext.getInstance("SSL");
		TrustManager[] tm={new MyX509TrustManager()};
		//初始化
		sslContext.init(null, tm, new java.security.SecureRandom());
		//獲取SSLSocketFactory物件
		SSLSocketFactory ssf=sslContext.getSocketFactory();
		URL url=new URL(requestUrl);
		HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod(requestMethod);
		if (null!=cookie) {
			conn.setRequestProperty("Cookie", cookie);
		}
		//設定當前例項使用的SSLSoctetFactory
		conn.setSSLSocketFactory(ssf);
		conn.connect();
		 // 獲取所有響應頭欄位
		 Map<String, List<String>> map = conn.getHeaderFields();
		 // 遍歷所有的響應頭欄位
		 for (String key : map.keySet()) {
		     System.out.println(key + "--->" + map.get(key));
		 }
		//往伺服器端寫內容
		if(null!=outputStr){
			OutputStream os=conn.getOutputStream();
			os.write(outputStr.getBytes("utf-8"));
			os.close();
		}
		
		//讀取伺服器端返回的內容
		InputStream is=conn.getInputStream();
		InputStreamReader isr=new InputStreamReader(is,"utf-8");
		BufferedReader br=new BufferedReader(isr);
		buffer=new StringBuffer();
		String line=null;
		while((line=br.readLine())!=null){
			buffer.append(line);
		}
		}catch(Exception e){
			e.printStackTrace();
		}
		return buffer.toString();
	}
}
package com.jxj.controller;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;

public class MyX509TrustManager implements X509TrustManager {

	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		// TODO Auto-generated method stub

	}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		// TODO Auto-generated method stub

	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		// TODO Auto-generated method stub
		return null;
	}

}
package com.jxj.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * 編碼與解碼
 * @author HANWENGANG
 *
 */
public class EncodeAndDecode {
	private static final Logger logger = LoggerFactory.getLogger(EncodeAndDecode.class);  
	/**
	 * 編碼
	 * @param str
	 * @param s
	 * @return
	 */
	public static String encode(String parameter,String coded){
		logger.info("--EncodeAndDecode--encode--statr--parameter="+parameter+"--coded="+coded);
		if(StringUtils.isNotBlank(parameter)&&StringUtils.isNotBlank(coded)){
			try {
				parameter = URLEncoder.encode(parameter,coded);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.error("--EncodeAndDecode--encode--Exception--"+e);
			}
			logger.info("--EncodeAndDecode--encode--end");
		}
		return parameter;
	}
	/**
	 * 解碼
	 */
	public static String decode(String parameter,String coded){
		logger.info("--EncodeAndDecode--decode--statr--parameter="+parameter+"--coded="+coded);
		if(StringUtils.isNotBlank(parameter)&&StringUtils.isNotBlank(coded)){
			try {
				parameter = URLDecoder.decode(parameter,coded);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.error("--EncodeAndDecode--decode--Exception--"+e);
			}
			logger.info("--EncodeAndDecode--decode--end");
		}
		return parameter;
		
	}
}
如果上面的行不通,看下面的。
package com.zhh.express.newman.Controller.solr;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping("searenByJXJ")
public class SearchByJDJingXiangJie {
	private static final Logger logger = LoggerFactory.getLogger(SearchByJDJingXiangJie.class);
	/**
	 * 關鍵字查詢jinxingjie商品,無分享賺
	 * ZHUZHIHONG
	 * @param searchKey
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="goodsListPlus",method = RequestMethod.POST)
	public String goodsListPlus(String searchKey,String pageIndex,String pageSize){
		
		logger.info("---SearchByJDJingXiangJie.goodsListPlus---start---searchKey="+searchKey+"---pageIndex="+pageIndex+"---pageSize="+pageSize);
		
		String searchUrl="https://xxx/xxx/xxx?g_tk=200330352&pageindex="+pageIndex+"&pagesize="+pageSize+"&key="+searchKeky+"&uniquespu=1&storestatus=1&ie=utf-8&text="+searchKey+"&_=15136719724";
		String resultStr=httpsRequestByGET(searchUrl);
		System.out.println("---處理前結果---"+resultStr);
		...此處省略我公司業務邏輯...
		
		return resultStr;
	}
	/*
	 * 處理https GET/POST請求
	 * 請求地址、請求方法、引數
	 * */
	public static String httpsRequestByGET(String requestUrl){
		StringBuffer buffer=null;
		try {
			HttpGet httpGet = new HttpGet(requestUrl);
			httpGet.addHeader("User-Agent", "Mozilla/5.0");
			CloseableHttpClient createSSLClientDefault = createSSLClientDefault();
			CloseableHttpResponse httpResponse = createSSLClientDefault.execute(httpGet);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
			        httpResponse.getEntity().getContent(),"utf-8"));

			String inputLine;
			buffer=new StringBuffer();
			while ((inputLine = reader.readLine()) != null) {
				buffer.append(inputLine);
			}
			reader.close();

			createSSLClientDefault.close();
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (UnsupportedOperationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return buffer.toString();
	}
	
	
	
	public static CloseableHttpClient createSSLClientDefault(){
		try {
		SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
		//信任所有
		public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		return true;
		}
		}).build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
		return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
		e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
		} catch (KeyStoreException e) {
		e.printStackTrace();
		}
		return HttpClients.createDefault();
		}

	
	
	
}