Use HttpClient to send a POST request to the HTTPS address

Source: Internet
Author: User

Jadyer [java]
Package com. jadyer. util;
 
Import java. io. IOException;
Import java. io. UnsupportedEncodingException;
Import java. security. KeyManagementException;
Import java. security. NoSuchAlgorithmException;
Import java. security. cert. CertificateException;
Import java. security. cert. X509Certificate;
Import java. util. ArrayList;
Import java. util. HashMap;
Import java. util. List;
Import java. util. Map;
 
Import javax.net. ssl. SSLContext;
Import javax.net. ssl. TrustManager;
Import javax.net. ssl. X509TrustManager;
 
Import org. apache. http. HttpEntity;
Import org. apache. http. HttpResponse;
Import org. apache. http. NameValuePair;
Import org. apache. http. ParseException;
Import org. apache. http. client. ClientProtocolException;
Import org. apache. http. client. HttpClient;
Import org. apache. http. client. entity. UrlEncodedFormEntity;
Import org. apache. http. client. methods. HttpPost;
Import org. apache. http. conn. scheme. Scheme;
Import org. apache. http. conn. ssl. SSLSocketFactory;
Import org. apache. http. impl. client. DefaultHttpClient;
Import org. apache. http. message. BasicNameValuePair;
Import org. apache. http. util. EntityUtils;
 
/**
* @ See ============================================== ========================================================== ======================================
* @ See: when developing an HTTPS application, you may encounter two situations:
* @ See 1. Either the test server does not have a valid SSL Certificate, and an exception is thrown when the client is connected.
* @ See javax.net. ssl. SSLPeerUnverifiedException: peer not authenticated
* @ See 2. Either the test server has an SSL certificate, but it may throw a heap of bad code for seven errors due to unknown reasons.
* @ See ============================================== ========================================================== ======================================
* @ See since we are using a connection created by the HttpComponents-Client-4.1.2 here, we need to tell it to use a different TrustManager
* @ See TrustManager is a class used to check whether a given certificate is valid.
* @ See the mode used by SSL is x.509... for this mode, Java has a specific TrustManager called X509TrustManager.
* @ See. Therefore, we create an X509TrustManager instance.
* @ See. In the X509TrustManager instance, if the certificate is invalid, TrustManager will throw CertificateException in its checkXXX () method.
* @ See since we want to accept all the certificates, we can simply ignore the exception in the method body in X509TrustManager.
* @ See: Create an SSLContext and use the X509TrustManager instance to initialize it.
* @ See: Create SSLSocketFactory through SSLContext, and register SSLSocketFactory with HttpClient.
* @ See ============================================== ========================================================== ======================================
* @ Create Jul 30,201 2 1:11:52
* @ Author Xuan Yu (http://blog.csdn/net/jadyer)
*/
Public class HttpClientUtil {
Public static void main (String [] args) throws Exception {
Map <String, String> params = new HashMap <String, String> ();
Params. put ("TransName", "IQSR ");
Params. put ("Plain", "transId = IQSR ~ | ~ OriginalorderId = 2012 ~ | ~ OriginalTransAmt = ~ | ~ MerURL = ");
Params. put ("Signature", "Signature ");
SendSSLPostRequest ("https://www.cebbank.com/per/QueryMerchantEpay.do", params );
}

/**
* Send a POST request to the HTTPS address
* @ Param reqURL: request address
* @ Param params Request Parameters
* @ Return response content
*/
@ SuppressWarnings ("finally ")
Public static String sendSSLPostRequest (String reqURL, Map <String, String> params ){
Long responseLength = 0; // response Length
String responseContent = null; // response content
HttpClient httpClient = new DefaultHttpClient (); // create a default httpClient instance
X509TrustManager xtm = new X509TrustManager () {// create TrustManager
Public void checkClientTrusted (X509Certificate [] chain, String authType) throws CertificateException {}
Public void checkServerTrusted (X509Certificate [] chain, String authType) throws CertificateException {}
Public X509Certificate [] getAcceptedIssuers () {return null ;}
};
Try {
// There is basically no big difference between TLS1.0 and SSL3.0. It can be roughly understood that TLS is the successor of SSL, but they use the same SSLContext
SSLContext ctx = SSLContext. getInstance ("TLS ");

// Use TrustManager to initialize the context. TrustManager is only used by the SSL Socket.
Ctx. init (null, new TrustManager [] {xtm}, null );

// Create SSLSocketFactory
SSLSocketFactory socketFactory = new SSLSocketFactory (ctx );

// Register SSLSocketFactory to our HttpClient through SchemeRegistry
HttpClient. getConnectionManager (). getSchemeRegistry (). register (new Scheme ("https", 443, socketFactory ));

HttpPost httpPost = new HttpPost (reqURL); // create HttpPost
List <NameValuePair> formParams = new ArrayList <NameValuePair> (); // construct the form parameters of the post request
For (Map. Entry <String, String> entry: params. entrySet ()){
FormParams. add (new BasicNameValuePair (entry. getKey (), entry. getValue ()));
}
HttpPost. setEntity (new UrlEncodedFormEntity (formParams, "UTF-8 "));

HttpResponse response = httpClient.exe cute (httpPost); // execute the POST request
HttpEntity entity = response. getEntity (); // get the response entity

If (null! = Entity ){
ResponseLength = entity. getContentLength ();
ResponseContent = EntityUtils. toString (entity, "UTF-8 ");
EntityUtils. consume (entity); // Consume response content
}
System. out. println ("request address:" + httpPost. getURI ());
System. out. println ("response status:" + response. getStatusLine ());
System. out. println ("response length:" + responseLength );
System. out. println ("response content:" + responseContent );
} Catch (KeyManagementException e ){
E. printStackTrace ();
} Catch (NoSuchAlgorithmException e ){
E. printStackTrace ();
} Catch (UnsupportedEncodingException e ){
E. printStackTrace ();
} Catch (ClientProtocolException e ){
E. printStackTrace ();
} Catch (ParseException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
HttpClient. getConnectionManager (). shutdown (); // close the connection and release resources
Return responseContent;
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.