当前位置:首页 > 开发 > 移动开发 > 正文

java 通过 SSL 发送 Post 请求(有参数)

发表于: 2015-01-09   作者:新的开始2015   来源:转载   浏览:
ssl
摘要: Java代码  收藏代码 package server.admin.login;  import java.io.BufferedReader;  import java.io.DataOutputStream;  import java.io.IOException;  import java.io.InputStreamReader;
Java代码  收藏代码
package server.admin.login; 
import java.io.BufferedReader; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
 
import java.net.URL; 
import java.net.URLEncoder; 
import java.security.cert.CertificateException; 
import java.security.cert.CertificateExpiredException; 
import java.security.cert.CertificateNotYetValidException; 
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; 
 
import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 
import org.apache.log4j.Logger;  
 
 
public class Test { 
     
    public static Logger log=Logger.getLogger("Test.class"); 
 
    public static SSLSocketFactory init() throws Exception { 
 
        class MyX509TrustManager implements X509TrustManager { 
             
            public MyX509TrustManager() throws Exception { 
                // do nothing 
            } 
 
            @Override 
            public void checkClientTrusted(X509Certificate[] chain, 
                    String authType) throws CertificateException { 
                 
            } 
 
            @Override 
            public void checkServerTrusted(X509Certificate[] chain, 
                    String authType) throws CertificateException { 
                 
                /*
                log.info("authType is " + authType);  
                log.info("cert issuers");  
                
                try{
                    for (int i = 0; i < chain.length; i++) {  
                        log.info("\t" + chain[i].getIssuerX500Principal().getName());  
                        log.info("\t" + chain[i].getIssuerDN().getName()); 
                        chain[i].checkValidity();
                    } 
                }catch(CertificateExpiredException ex){
                    log.error("checkDate: Certificate has expired");    
                }catch(CertificateNotYetValidException yet){
                    log.error("checkDate: Certificate is not yet valid");
                }catch(Exception ee){
                    log.error("Error: "+ee.getMessage());
                }*/ 
 
            } 
 
            @Override 
            public X509Certificate[] getAcceptedIssuers() { 
                return new X509Certificate[] {}; 
            } 
        } 
        TrustManager[] tm = { new MyX509TrustManager() }; 
         
        System.setProperty("https.protocols", "TLSv1"); 
        SSLContext sslContext = SSLContext.getInstance("TLSv1","SunJSSE"); 
        sslContext.init(null, tm, new java.security.SecureRandom()); 
        SSLSocketFactory ssf = sslContext.getSocketFactory(); 
         
        return ssf; 
    } 
     
    /**
     * 
     * @param POST_URL
     * @param token
     * @return
     * @throws IOException
     */ 
    private static boolean sendHttpsPost(String POST_URL,String token)throws IOException{ 
         
        boolean returnVal=false; 
          
        URL myURL = new URL(POST_URL); 
         
        HttpsURLConnection con = (HttpsURLConnection) myURL.openConnection(); 
         
        HostnameVerifier hostNameVerify = new HostnameVerifier() 
        { 
            /**
             * Always return true
             */ 
            public boolean verify(String urlHostName, SSLSession session) 
            { 
                return true; 
            } 
        }; 
        //HttpsURLConnection.setDefaultHostnameVerifier(hostNameVerify); 
        con.setHostnameVerifier(hostNameVerify); 
        try { 
            con.setSSLSocketFactory(init()); 
        } catch (Exception e1) { 
            // throw out the exception 
            throw new IOException(e1); 
        } 
         
        con.setDoOutput(true);     
        con.setDoInput(true);     
        con.setRequestMethod("POST");     
        con.setUseCaches(false);     
        con.setInstanceFollowRedirects(true);     
        con.setRequestProperty("Content-Type "," application/x-www-form-urlencoded ");     
 
        con.connect();  
         
        DataOutputStream out = new DataOutputStream(con.getOutputStream());     
 
        String content = "authenticityToken="+ URLEncoder.encode(token, "utf-8");     
         
        out.writeBytes(content);     
 
        out.flush();     
        out.close();  
     
        BufferedReader reader = new BufferedReader(new InputStreamReader(     
        con.getInputStream()));     
        String line;     
                 
        while ((line = reader.readLine()) != null) {     
             
            if(line.equalsIgnoreCase("ok")) 
                returnVal=true; 
            else 
                returnVal=false; 
        }     
        reader.close();     
        con.disconnect(); 
     
         
        return returnVal; 
    } 
    public static boolean readContentFromPost(String POST_URL,String token) throws IOException {     
          
            TestLogger.setLog4jLogger(log); 
             
            POST_URL=POST_URL+"validate"; 
             
            return sendHttpsPost(POST_URL,token); 
    } 
 
     
 
 

java 通过 SSL 发送 Post 请求(有参数)

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
GET与POST方式发送请求参数 getAndPostExample.html清单: <!DOCTYPE html PUBLIC "-//W3C//DTD
headers-custom header 增加一个Content-type: application/x-www-form-urlencoded 然后在body里面
GET与POST方式发送请求参数 getAndPostExample.html清单: <!DOCTYPE html PUBLIC "-//W3C//DTD
GET与POST方式发送请求参数 getAndPostExample.html清单: <!DOCTYPE html PUBLIC "-//W3C//DTD
在某些情况下,需要用Java applicatioin来模拟form,向服务器(本文以servlet为例)发送http post请求
在某些情况下,需要用Java applicatioin来模拟form,向服务器(本文以servlet为例)发送http post请求
在某些情况下,需要用Java applicatioin来模拟form,向服务器(本文以servlet为例)发送http post请求
在某些情况下,需要用Java applicatioin来模拟form,向服务器(本文以servlet为例)发送http post请求
通过SoapUI发送POST请求,请求的body是JSON格式的数据: data={"currentDate":"2015-06-19","reset"
使用Fiddler发送POST请求 在测试过程中,有时会遇到需要修改请求中带的参数,去验证权限的安全问题
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号