不多说,直接上代码。
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> 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();
}
}