Java uses httpclient for Post and get requests (HTTPS) __javase

Source: Internet
Author: User

Currently, to provide an interface for another project, the interface is implemented with an HTTP URL, with the original idea that another project is requesting it with a jquery post.

However, it is possible that another project is deployed on another machine, then there is a cross-domain problem, and jquery's post request is not allowed across domains.

At this time, can only be enough to httpclient packet request, and because the requested URL is HTTPS, in order to avoid the need for certificates, so with a class inheritance Defaulthttpclient class, ignoring the checksum process.

1. Write a sslclient class, inherit to HttpClient

Import java.security.cert.CertificateException;  
Import Java.security.cert.X509Certificate;  
Import Javax.net.ssl.SSLContext;  
Import Javax.net.ssl.TrustManager;  
Import Javax.net.ssl.X509TrustManager;  
Import Org.apache.http.conn.ClientConnectionManager;  
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.impl.client.DefaultHttpClient;  
        The httpclient public class Sslclient extends for HTTPS requests defaulthttpclient{public sslclient () throws exception{  
        Super ();  
        Sslcontext CTX = sslcontext.getinstance ("TLS"); X509trustmanager TM = new X509trustmanager () {@Override public void Checkclienttruste  
                D (x509certificate[] chain, String authtype) throws Certificateexception {} @Override public void checkservertrusted (x509cErtificate[] chain, String authtype) throws Certificateexception {}  
                @Override public x509certificate[] Getacceptedissuers () {return null;  
        }  
        };  
        Ctx.init (NULL, new TRUSTMANAGER[]{TM}, NULL);  
        Sslsocketfactory SSF = new Sslsocketfactory (ctx,sslsocketfactory.allow_all_hostname_verifier);  
        Clientconnectionmanager CCM = This.getconnectionmanager ();  
        schemeregistry sr = Ccm.getschemeregistry ();  
    Sr.register (New Scheme ("https", 443, SSF));   }  
}


2. Write a class that uses httpclient to send a POST request

Import java.util.ArrayList;  
Import Java.util.Iterator;  
Import java.util.List;  
Import Java.util.Map;  
Import Java.util.Map.Entry;  
Import org.apache.http.HttpEntity;  
Import Org.apache.http.HttpResponse;  
Import Org.apache.http.NameValuePair;  
Import org.apache.http.client.HttpClient;  
Import org.apache.http.client.entity.UrlEncodedFormEntity;  
Import Org.apache.http.client.methods.HttpPost;  
Import Org.apache.http.message.BasicNameValuePair;  
Import Org.apache.http.util.EntityUtils; * * Tool class with httpclient for post requests/public class Httpclientutil {public string doPost (string url,map<string,s  
        Tring> map,string CharSet) {httpclient httpclient = null;  
        HttpPost httppost = null;  
        String result = null;  
            try{httpclient = new Sslclient ();  
            HttpPost = new HttpPost (URL);  
            Set parameter list<namevaluepair> List = new arraylist<namevaluepair> (); Iterator itErator = Map.entryset (). iterator (); while (Iterator.hasnext ()) {entry<string,string> Elem = (entry<string, string>) iterator.next  
                ();  
            List.add (New Basicnamevaluepair (Elem.getkey (), Elem.getvalue ())); } if (List.size () > 0) {urlencodedformentity entity = new Urlencodedformentity (List,char  
                Set);  
            Httppost.setentity (entity);  
            } HttpResponse response = Httpclient.execute (HttpPost);  
                if (response!= null) {httpentity resentity = response.getentity ();  
                if (resentity!= null) {result = Entityutils.tostring (Resentity,charset);  
        }}catch (Exception ex) {ex.printstacktrace ();  
    return result;   }  
}



3. Invoke the test code for the POST request

import Java.util.HashMap;  
Import Java.util.Map;  
    Testing the interface public class Testmain {private String URL = "https://192.168.1.101/";  
    Private String charset = "Utf-8";  
      
    Private Httpclientutil httpclientutil = null;  
    Public Testmain () {httpclientutil = new httpclientutil ();  
        public void Test () {String httporgcreatetest = url + ' httporg/create ';  
        map<string,string> Createmap = new hashmap<string,string> ();  
        Createmap.put ("Authuser", "* * *");  
        Createmap.put ("Authpass", "* * *");  
        Createmap.put ("Orgkey", "* * *");  
        Createmap.put ("OrgName", "* * *");  
        String Httporgcreatetestrtn = Httpclientutil.dopost (Httporgcreatetest,createmap,charset);  
    SYSTEM.OUT.PRINTLN ("Result:" +httporgcreatetestrtn);  
        public static void Main (string[] args) {Testmain main = new Testmain ();  
    Main.test (); }  
}  



4.GET Request Mode

/**
	 * Send GET request
	 * @param url       link Address
	 * @param charset   character encoding, if NULL then default Utf-8
	 * @return *
	public string Doget (String url,string charset) {
		if (null = = CharSet) {
			charset = "Utf-8";
		}
		HttpClient httpclient = null;
		HttpGet httpget= null;
		String result = null;
		
		try {
			httpclient = new Sslclient ();
			HttpGet = new HttpGet (URL);
			
			HttpResponse response = Httpclient.execute (httpget);
			if (response!= null) {
				httpentity resentity = response.getentity ();
				if (resentity!= null) {Result
					= entityutils.tostring (Resentity,charset);
				}
			\
		catch (Exception E ) {
			e.printstacktrace ();
		}
		
		return result;
	}




httpClient4.2 's jar package download path: http://download.csdn.net/detail/hqmryang/4582440#comment

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.