赞
踩
用过jersey的post访问HTTPS是报cert异常
提示:这里填写该问题的具体解决方案:
- import com.sun.jersey.api.client.Client;
- import com.sun.jersey.api.client.ClientResponse;
- import com.sun.jersey.api.client.WebResource;
- import com.sun.jersey.api.client.config.ClientConfig;
- import com.sun.jersey.api.client.config.DefaultClientConfig;
- import com.sun.jersey.client.urlconnection.HTTPSProperties;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.codec.binary.Base64;
- import org.apache.commons.codec.digest.HmacUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import javax.net.ssl.*;
- import java.io.UnsupportedEncodingException;
- import java.net.URLEncoder;
- import java.security.KeyManagementException;
- import java.security.NoSuchAlgorithmException;
- import java.security.SecureRandom;
- import java.security.cert.X509Certificate;
- import java.util.Date;
- import java.util.Random;
-
-
- @Service
- @Slf4j
- public class AccessService {
-
-
-
-
- public String postUrl(String url , String param){
- log.info("postUrl-url:{},param:{}",url,param);
-
- Client client = null;
- ClientResponse response = null;
-
- try {
- ClientConfig config = init();
- client = Client.create(config);
- client.setFollowRedirects(true);
- WebResource webResource = client.resource(url);
-
- response = webResource.header("Authorization",authHeader).type("application/json").post(ClientResponse.class, param);
- String jsonString = response.getEntity(String.class);
- log.warn("http返回码:{},http消息体为:{}" , response.getStatus(),jsonString);
- if (response.getStatus() == 200) {
-
- return jsonString;
- } else {
- throw new RuntimeException( "http请求异常,http返回码:" + response.getStatus() + ";http消息体为:" + jsonString);
- }
-
- }catch (Exception ex){
- log.warn("postUrl:"+ex.getMessage());
- }finally {
- if (response != null) {
- response.close();
- }
- if (client != null) {
- client.destroy();
- }
- }
-
- return "";
- }
- /**
- * 跳过https
- * */
- public static ClientConfig init() throws NoSuchAlgorithmException, KeyManagementException {
- SSLContext context = SSLContext.getInstance("SSL");
- TrustManager[] trustAllCerts = new TrustManager[] {
- new X509TrustManager() {
- public X509Certificate[] getAcceptedIssuers() {
- return null;
- }
- @Override
- public void checkClientTrusted(X509Certificate[] certs, String authType) {}
- @Override
- public void checkServerTrusted(X509Certificate[] certs, String authType) {}
- }
- };
-
- context.init(null, trustAllCerts, new SecureRandom());
- HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
-
- ClientConfig config = new DefaultClientConfig();
- config.getProperties().put(
- HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
- new HTTPSProperties(new HostnameVerifier() {
- public boolean verify(String s, SSLSession sslSession) {
- return true;
- }
- }, context)
- );
- return config;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。