2
回答
HttpClient如何发送https请求?
终于搞明白,存储TCO原来是这样算的>>>   

网站使用的证书:此网站使用了 SHA-1 证书

希望各位大侠给个例子

举报
清尘V
发帖于3年前 2回/5K+阅
共有2个答案 最后回答: 3年前

其中有一些自己写的方法,直接从以前项目拷贝出来的,你看着修改一下把

注:双向验证,你可以删除一个本地的Key,就可以了


两个类,第一个用来创建CloseableHttpClient的

另一个是POST、GET、UPLOAD封装


import com.temborn.polysync.client.utils.MyUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;


import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;


/**
 * Created by KisChang on 2015/3/10.
 * 内部使用的Https连接创建
 */
class HttpsClientFactory {


    private static HttpsClientFactory _Instance = null;
    private static SSLConnectionSocketFactory sslFactory = null;


    private HttpsClientFactory(){}


    public static HttpsClientFactory init(KeyStoreType clientType,String clientKeyPath,String clientKeyPw,
                                          KeyStoreType trustType,String trustKeyPath,String trustKeyPw){
        if(_Instance != null){
            return _Instance;
        }
        HttpsClientFactory factory = new HttpsClientFactory();
        KeyStore trustStore = null;
        KeyStore clientStore = null;
        FileInputStream trustInStream = null;
        FileInputStream clientInStream = null;
        try {
            clientStore = KeyStore.getInstance(clientType.getValue());
            clientInStream = new FileInputStream(new File(clientKeyPath));
            clientStore.load(clientInStream, clientKeyPw.toCharArray());


            trustStore = KeyStore.getInstance(trustType.getValue());
            trustInStream = new FileInputStream(new File(trustKeyPath));
            trustStore.load(trustInStream,trustKeyPw.toCharArray());


            SSLContext sslcontext = SSLContexts
                    .custom()
                    .loadKeyMaterial(clientStore,clientKeyPw.toCharArray())
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
                    .build();
            sslFactory = new SSLConnectionSocketFactory(sslcontext
                    , new String[] { "TLSv1" }, null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Load SSL KeyStore Error!!!");
        } finally {
            MyUtils.closeInputStream(trustInStream);
            MyUtils.closeInputStream(clientInStream);
        }
        _Instance = factory;
        return factory;
    }


    public CloseableHttpClient build(){
        return HttpClients
                .custom()
                .setSSLSocketFactory(sslFactory)
                .build();
    }
}




import com.alibaba.fastjson.JSON;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 完成基于SSL双向认证的Https请求的处理
 */
public class HttpsClientUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpsClientUtils.class);


    private String charSet;


    private String clientKey;
    private KeyStoreType clientType;
    private String clientPassword;


    private String trustKey;
    private KeyStoreType trustType;
    private String trustPassword;


    /**
     * 所有配置改成从配置文件加载
     */
    public HttpsClientUtils() {
        this.charSet =          Context.getContext().getConf(Context.CLIENT_HTTPS_CHARSET);
        this.clientKey =        Context.getContext().getConf(Context.CLIENT_HTTPS_CLIENT_KEY_PATH);
        this.clientPassword =   Context.getContext().getConf(Context.CLIENT_HTTPS_CLIENT_KEY_PASSWORD);
        this.trustKey =         Context.getContext().getConf(Context.CLIENT_HTTPS_SERVER_KEY_PATH);
        this.trustPassword =    Context.getContext().getConf(Context.CLIENT_HTTPS_SERVER_KEY_PASSWORD);
        this.clientType =   KeyStoreType.valueOf(Context.getContext().getConf(Context.CLIENT_HTTPS_CLIENT_KEY_TYPE));
        this.trustType =    KeyStoreType.valueOf(Context.getContext().getConf(Context.CLIENT_HTTPS_SERVER_KEY_TYPE));
    }


    public HttpsClientUtils(String clientKey, KeyStoreType clientType, String clientPassword, String trustKey, KeyStoreType trustType, String trustPassword) {
        this("UTF-8",clientKey,clientType,clientPassword,trustKey,trustType,trustPassword);
    }


    public HttpsClientUtils(String charSet, String clientKey, KeyStoreType clientType, String clientPassword, String trustKey, KeyStoreType trustType, String trustPassword) {
        this.charSet = charSet;
        this.clientKey = clientKey;
        this.clientType = clientType;
        this.clientPassword = clientPassword;
        this.trustKey = trustKey;
        this.trustType = trustType;
        this.trustPassword = trustPassword;
    }


    /**
* post方式提交表单
*/
    public String post(String url, Map<String, String> param) {
        String result = null;
CloseableHttpClient httpClient = HttpsClientFactory
                .init(clientType,clientKey,clientPassword,trustType,trustKey,trustPassword).build();
// 创建httpPost
HttpPost httppost = new HttpPost(url);
// 创建参数队列  
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
try {
            if(param != null && !param.isEmpty()){  //如果参数不为空的话,添加参数
                for(Map.Entry<String,String> ent : param.entrySet()){
                    formParams.add(new BasicNameValuePair(ent.getKey(),ent.getValue()));
                }
                UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formParams, this.charSet);
                httppost.setEntity(uefEntity);
            }
CloseableHttpResponse response = httpClient.execute(httppost);
            if(response.getStatusLine().getStatusCode() == 200){
                try {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        result = EntityUtils.toString(entity,this.charSet);
                    }
                } finally {
                    response.close();
                }
            }else{
                logger.error("请求出错,错误码是:"+response.getStatusLine().getStatusCode());
            }
} catch (Exception e) {
e.printStackTrace();
} finally {// 关闭连接,释放资源
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
        return result;
}


/**
* 发送 get请求
*/
public String get(String url,Map<String,String> param) {
        String result = null;
CloseableHttpClient httpClient = HttpsClientFactory
                .init(clientType,clientKey,clientPassword,trustType,trustKey,trustPassword).build();
try {
// 创建httpget.
            if (param != null && !param.isEmpty()){
                StringBuffer sb = new StringBuffer();
                sb.append(url);
                sb.append("?");
                for(Map.Entry<String,String> ent : param.entrySet()){
                    sb.append(ent.getKey());
                    sb.append("=");
                    sb.append(URLEncoder.encode(ent.getValue(),this.charSet));
                }
                url = sb.toString();
                System.out.println(url);
            }
            HttpGet httpget = new HttpGet(url);
// 执行get请求
CloseableHttpResponse response = httpClient.execute(httpget);
            if(response.getStatusLine().getStatusCode() == 200){
                try {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        result = EntityUtils.toString(entity,this.charSet);
                    }
                } finally {
                    response.close();
                }
            }else{
                logger.error("请求出错,错误码是:"+response.getStatusLine().getStatusCode());
            }
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
        return result;
}
/**
* 上传文件
*/
public String upload(String url,Map<String,List<byte[]>> binMap,Map<String,List<File>> fileMap,Map<String,String> paramMap) {
        String result = null;
CloseableHttpClient httpClient = HttpsClientFactory
                .init(clientType,clientKey,clientPassword,trustType,trustKey,trustPassword).build();
try {
HttpPost httppost = new HttpPost(url);


            MultipartEntityBuilder reqEntityBuilder = MultipartEntityBuilder.create();
            boolean hasParam = false;
            if(binMap != null && !binMap.isEmpty()){
                for(Map.Entry<String,List<byte[]>> ent : binMap.entrySet()){
                    for(byte[] itm : ent.getValue()){
                        reqEntityBuilder.addBinaryBody(ent.getKey(),itm);
                    }
                    hasParam = true;
                }
            }
            if(fileMap != null && !fileMap.isEmpty()){
                for(Map.Entry<String,List<File>> ent : fileMap.entrySet()){
                    for(File itm : ent.getValue()){
                        reqEntityBuilder.addPart(ent.getKey(), new FileBody(itm));
                    }
                    hasParam = true;
                }
            }
            if(paramMap != null && !paramMap.isEmpty()){
                reqEntityBuilder.setCharset(Charset.forName(this.charSet));
                for(Map.Entry<String,String> ent : paramMap.entrySet()){
                    reqEntityBuilder.addPart(ent.getKey(), new StringBody(ent.getValue(),ContentType.create(ContentType.DEFAULT_TEXT.getMimeType(), Charset.forName(this.charSet))));
                }
            }
            if(!hasParam){
                logger.error("Not Found File Param!!!");
            }


HttpEntity reqEntity = reqEntityBuilder.build();
httppost.setEntity(reqEntity);


CloseableHttpResponse response = httpClient.execute(httppost);
            if(response.getStatusLine().getStatusCode() == 200){
                try {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        result = EntityUtils.toString(resEntity,this.charSet);
                    }
                    EntityUtils.consume(resEntity);
                } finally {
                    response.close();
                }
            }else{
                logger.error("请求出错,错误码是:"+response.getStatusLine().getStatusCode());
            }
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
        return result;
}


}
--- 共有 1 条评论 ---
汉东反贪局局长侯亮平直接说一下思路不行么,授之以鱼不如授之以渔 3年前 回复
顶部