第一种方法,适用于httpclient4.X 里边有get和post两种方法供你发送请求使用。导入证书发送请求的在这里就不说了,网上到处都是

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.HostNameResolver;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/*
 * author:haungxuebin
 * 云南新接口
 * 
 */
public class HttpClientSendPost {
private static DefaultHttpClient client;
 /** 
     * 访问https的网站 
     * @param httpclient 
     */  
    private static void enableSSL(DefaultHttpClient httpclient){  
        //调用ssl  
         try {  
                SSLContext sslcontext = SSLContext.getInstance("TLS");  
                sslcontext.init(null, new TrustManager[] { truseAllManager }, null);  
                SSLSocketFactory sf = new SSLSocketFactory(sslcontext);  
                sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
                Scheme https = new Scheme("https", sf, 443);  
                httpclient.getConnectionManager().getSchemeRegistry().register(https);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
    }  
    /** 
     * 重写验证方法,取消检测ssl 
     */  
    private static TrustManager truseAllManager = new X509TrustManager(){  
  
        public void checkClientTrusted(  
                java.security.cert.X509Certificate[] arg0, String arg1)  
                throws CertificateException {  
            // TODO Auto-generated method stub  
              
        }  
  
        public void checkServerTrusted(  
                java.security.cert.X509Certificate[] arg0, String arg1)  
                throws CertificateException {  
            // TODO Auto-generated method stub  
              
        }  
  
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
            // TODO Auto-generated method stub  
            return null;  
        }  
          
    }; 
/**
* HTTP Client Object,used HttpClient Class before(version 3.x),but now the
* HttpClient is an interface
*/

public static String sendXMLDataByGet(String url,String xml){
   // 创建HttpClient实例     
        if (client == null) {
// Create HttpClient Object
client = new DefaultHttpClient();
enableSSL(client);
}
        StringBuilder urlString=new StringBuilder();
        urlString.append(url);
        urlString.append("?");
        System.out.println("getUTF8XMLString(xml):"+getUTF8XMLString(xml));
        try {
urlString.append(URLEncoder.encode( getUTF8XMLString(xml) , "UTF-8" ));
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
        String urlReq=urlString.toString();
        // 创建Get方法实例     
        HttpGet httpsgets = new HttpGet(urlReq);

String strRep="";
try {
HttpResponse response = client.execute(httpsgets);    
HttpEntity entity = response.getEntity();

if (entity != null) { 
strRep = EntityUtils.toString(response.getEntity());
   // Do not need the rest    
   httpsgets.abort();    
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}  
        return strRep;
    }

/**
* Send a XML-Formed string to HTTP Server by post method

* @param url
*            the request URL string
* @param xmlData
*            XML-Formed string ,will not check whether this string is
*            XML-Formed or not
* @return the HTTP response status code ,like 200 represents OK,404 not
*         found
* @throws IOException
* @throws ClientProtocolException
*/
public static String sendXMLDataByPost(String url, String xmlData)
throws ClientProtocolException, IOException {
if (client == null) {
// Create HttpClient Object
client = new DefaultHttpClient();
enableSSL(client);
}
client.getParams().setParameter("http.protocol.content-charset",
HTTP.UTF_8);
client.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
client.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
client.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET,
HTTP.UTF_8);

// System.out.println(HTTP.UTF_8);
// Send data by post method in HTTP protocol,use HttpPost instead of
// PostMethod which was occurred in former version
// System.out.println(url);
HttpPost post = new HttpPost(url);
post.getParams().setParameter("http.protocol.content-charset",
HTTP.UTF_8);
post.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
post.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
post.getParams()
.setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);

// Construct a string entity
StringEntity entity = new StringEntity(getUTF8XMLString(xmlData), "UTF-8");
entity.setContentType("text/xml;charset=UTF-8");
entity.setContentEncoding("UTF-8");
// Set XML entity
post.setEntity(entity);
// Set content type of request header
post.setHeader("Content-Type", "text/xml;charset=UTF-8");
// Execute request and get the response
HttpResponse response = client.execute(post);
HttpEntity entityRep = response.getEntity(); 
String strrep="";
        if (entityRep != null) {     
            strrep = EntityUtils.toString(response.getEntity());
            // Do not need the rest    
            post.abort();    
        }  
// Response Header - StatusLine - status code
// statusCode = response.getStatusLine().getStatusCode();
return strrep;
}
/**
* Get XML String of utf-8

* @return XML-Formed string
*/
public static String getUTF8XMLString(String xml) {
// A StringBuffer Object
StringBuffer sb = new StringBuffer();
sb.append(xml);
String xmString = "";
try {
xmString = new String(sb.toString().getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return to String Formed
return xmString.toString();
}

}

第二种仿http的不用HttpClient 都是jdk自带的包

package org.sp.sc.util;

import Java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.NET.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.Net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
     * 无视Https证书是否正确的JavaHttp Client
     * 
     * 
     * @author huangxuebin
     *
     * @create 2012.8.17
     * @version 1.0
     */
public class HttpsUtil {

/**
     * 忽视证书HostName
     */
    private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
        public boolean verify(String s, SSLSession sslsession) {
            System.out.println("WARNING: Hostname is not matched for cert.");
            return true;
        }
    };

/**
     * Ignore Certification
     */
    private static TrustManager ignoreCertificationTrustManger = new X509TrustManager() {

private X509Certificate[] certificates;

@Override
        public void checkClientTrusted(X509Certificate certificates[],
                String authType) throws CertificateException {
            if (this.certificates == null) {
                this.certificates = certificates;
                System.out.println("init at checkClientTrusted");
            }

}

@Override
        public void checkServerTrusted(X509Certificate[] ax509certificate,
                String s) throws CertificateException {
            if (this.certificates == null) {
                this.certificates = ax509certificate;
                System.out.println("init at checkServerTrusted");
            }

//            for (int c = 0; c < certificates.length; c++) {
//                X509Certificate cert = certificates[c];
//                System.out.println(" Server certificate " + (c + 1) + ":");
//                System.out.println("  Subject DN: " + cert.getSubjectDN());
//                System.out.println("  Signature Algorithm: "
//                        + cert.getSigAlgName());
//                System.out.println("  Valid from: " + cert.getNotBefore());
//                System.out.println("  Valid until: " + cert.getNotAfter());
//                System.out.println("  Issuer: " + cert.getIssuerDN());
//            }

}

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

};

public static String getMethod(String urlString) {

ByteArrayOutputStream buffer = new ByteArrayOutputStream(512);
        try {

URL url = new URL(urlString);

/*
             * use ignore host name verifier
             */
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

// Prepare SSL Context
            TrustManager[] tm = { ignoreCertificationTrustManger };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());

// 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            connection.setSSLSocketFactory(ssf);
            
            InputStream reader = connection.getInputStream();
            byte[] bytes = new byte[512];
            int length = reader.read(bytes);

do {
                buffer.write(bytes, 0, length);
                length = reader.read(bytes);
            } while (length > 0);

// result.setResponseData(bytes);
            System.out.println(buffer.toString());
            reader.close();
            
            connection.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
        }
        String repString= new String (buffer.toByteArray());
        return repString;
    }

//    public static void main(String[] args) {
//        String urlString = "https://218.202.0.241:8081/XMLReceiver";
//        String output = new String(HttpsUtil.getMethod(urlString));
//        System.out.println(output);
//    }
}

关于httpclient 请求https (如何绕过证书验证)的更多相关文章

  1. 轻松把玩HttpClient之配置ssl,采用绕过证书验证实现https

    上篇文章说道httpclient不能直接访问https的资源,这次就来模拟一下环境,然后配置https测试一下.在前面的文章中,分享了一篇自己生成并在tomcat中配置ssl的文章<Tomcat ...

  2. [Java] 绕过证书验证调 HTTPS 接口时报 “SSLHandshakeException: DHPublicKey does not comply to algorithm constraints”的解决办法

    作者: zyl910 一.缘由 最近有在对接一个无证书的HTTPS接口时,总是收到"SSLHandshakeException: DHPublicKey does not comply to ...

  3. [转]java 关于httpclient 请求https (如何绕过证书验证)

    原文:http://www.blogjava.net/hector/archive/2012/10/23/390073.html 第一种方法,适用于httpclient4.X 里边有get和post两 ...

  4. httpclient绕过证书验证进行HTTPS请求

    http请求是我们常用的一种web应用的应用层协议,但是由于它的不安全性,现在正在逐渐向https协议过渡.https协议是在http的基础上进行了隧道加密,加密方式有SSL和TLS两种.当serve ...

  5. linux 测试 get 请求 跳过SSL证书验证

    Linux 下测试 get 请求: curl : curl "http://www.qq.com" # 标准输出页面内容 curl -i "http://www.qq.c ...

  6. Axis 1 https(SSL) client 证书验证错误ValidatorException workaround

    Axis 1.x 编写的client在测试https的webservice的时候, 由于client 代码建立SSL连接的时候没有对truststore进行设置,在与https部署的webservic ...

  7. Android 实现 HttpClient 请求Https

    如题,默认下,HttpClient是不能请求Https的,需要自己获取 private static final int SET_CONNECTION_TIMEOUT = 5 * 1000; priv ...

  8. java请求https地址如何绕过证书验证?

    原文http://www.blogjava.net/hector/archive/2012/10/23/390073.html 第一种方法,适用于httpclient4.X 里边有get和post两种 ...

  9. 请求https前缀的网站验证SSL证书的解决方案之一

    from requests.packages.urllib3.exceptions import InsecureRequestWarning # 禁用安全请求警告requests.packages. ...

随机推荐

  1. code forces 996D Suit and Tie

    D. Suit and Tie time limit per test 2 seconds memory limit per test 256 megabytes input standard inp ...

  2. Educational Codeforces Round 42 (Rated for Div. 2) C

    C. Make a Square time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...

  3. VMware Storage VMotion概述及功能

    可以跨存储阵列实时迁移虚拟机磁盘文件.VMware Storage VMotion 使您可以在共享存储位置之间和跨共享存储位置重新分配虚拟机磁盘文件,同时保证连续的服务供应和事务处理的完整性. 1.可 ...

  4. POST JSON fails with 415 Unsupported media type, SpringMVC

    网上的解决办法非常多,但是大多不靠谱. 归结原因:SpringMVC 无法通过 httprequest headers 中的 Content-Type 和 Accept 匹配到对应的HttpMessa ...

  5. [HNOI2002] 公交车路线

    题目背景 在长沙城新建的环城公路上一共有8个公交站,分别为A.B.C.D.E.F.G.H.公共汽车只能够在相邻的两个公交站之间运行,因此你从某一个公交站到另外一个公交站往往要换几次车,例如从公交站A到 ...

  6. Linux 根据组来划分账号,根据部门同一账号的组,同一组下拥有同一权限

    #新机器添加 #创建部门组与账号 useradd testgroup #创建员工账号加入到部门组里 useradd -g testgroup user1 #员工在/data目录下创建的默认权限为774 ...

  7. 高级列表控件ListCtrl关联的MFC中的类:CListCtrl

    高级列表控件ListCtrl关联的MFC中的类:CListCtrl■ 报表样式ListCtrl常用操作:1.添加列标题头:InsertColumn2.获取与设置列宽:GetColumnWidth.Se ...

  8. python collections(容器)模块

    原文:http://docs.pythontab.com/interpy/collections/collections/ 容器(Collections) Python附带一个模块,它包含许多容器数据 ...

  9. jQuery Lazy Load图片懒加载

    传送门:官网地址,jQuery Lazy Load v1.7.2下载,Github 使用方法: 1.引用js文件 <script src="jquery.js">< ...

  10. Spring:特殊数据类型的属性注入(基于配置文件)

    该处提到的特殊数据类型指的是除了基础数据类型和String以外的其他常用的数据类型,如:List.Map.Set.以及pojo对象等.则我们创建的Person类定义为: package bjtu.we ...