Send a POST request to an HTTPS address using httpclient 4.1.2

Source: Internet
Author: User
Tags ssl certificate
send a POST request to an HTTPS address using httpclientPackage 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 often encounter two situations when developing HTTPS applications
* @see 1, either the test server does not have a valid SSL certificate, and the client will throw an exception when it connects
* @see Javax.net.ssl.SSLPeerUnverifiedException:peer Not authenticated
* @see 2, or the test server has an SSL certificate, but may be due to various unknown reasons, it will still throw a heap of bad code seven bad exception
* @see =====================================================================================================
* @see because we're using httpcomponents-client-4.1.2 to create a connection, we're going to tell it to use a different TrustManager
* @see TrustManager is a class for checking whether a given certificate is valid
* The mode used for @see SSL is X.509 .... For this pattern, Java has a specific trustmanager called X509trustmanager
* @see So we create a X509trustmanager instance of our own
* @see and in the X509trustmanager instance, if the certificate is invalid, the TrustManager is thrown in its checkxxx () method certificateexception
* @see Since we're going to accept all the certificates, it's OK to x509trustmanager the method in the body without throwing an exception.
* @see and then create a sslcontext and use the X509trustmanager instance to initialize the
* @see then create sslsocketfactory through Sslcontext, and finally register sslsocketfactory to httpclient.
* @see =====================================================================================================
* @create 1:11:52 PM
* @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", "9b759887e6ca9d4c24509d22ee4d22494d0dd2dfbdbeaab3545c1acee62eec7");
Sendsslpostrequest ("Https://www.cebbank.com/per/QueryMerchantEpay.do", params);
}

/**
* Send POST request to 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 {
TLS1.0 and SSL3.0 are basically not very different, and they can be roughly understood as TLS are the inheritors of SSL, but they use the same sslcontext
Sslcontext CTX = sslcontext.getinstance ("TLS");

Use TrustManager to initialize the context, TrustManager is only used by an SSL socket
Ctx.init (NULL, new TRUSTMANAGER[]{XTM}, NULL);

Create Sslsocketfactory
Sslsocketfactory socketfactory = new Sslsocketfactory (CTX);

Register Sslsocketfactory to our httpclient via Schemeregistry.
Httpclient.getconnectionmanager (). Getschemeregistry (). Register (New Scheme ("https", 443, socketfactory));

HttpPost HttpPost = new HttpPost (Requrl); Create HttpPost
list<namevaluepair> formparams = new arraylist<namevaluepair> (); Building form parameters for post requests
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.execute (HttpPost); Perform a POST request
httpentity entity = response.getentity (); Get 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 the resource
return responsecontent;
}
}

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.