Java uses httpclient for post requests (HTTPS)

Source: Internet
Author: User

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

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

At this time, only enough httpclient package to request, and because the URL of the request is HTTPS, in order to avoid the need for certificates, so a class inherits the Defaulthttpclient class, ignoring the validation process.

1. Write a sslclient class, inherit to HttpClient

[Java]View PlainCopy 
  1. Import java.security.cert.CertificateException;
  2. Import Java.security.cert.X509Certificate;
  3. Import Javax.net.ssl.SSLContext;
  4. Import Javax.net.ssl.TrustManager;
  5. Import Javax.net.ssl.X509TrustManager;
  6. Import Org.apache.http.conn.ClientConnectionManager;
  7. Import Org.apache.http.conn.scheme.Scheme;
  8. Import Org.apache.http.conn.scheme.SchemeRegistry;
  9. Import Org.apache.http.conn.ssl.SSLSocketFactory;
  10. Import org.apache.http.impl.client.DefaultHttpClient;
  11. HttpClient for HTTPS requests
  12. Public class Sslclient extends defaulthttpclient{
  13. Public sslclient () throws exception{
  14. super ();
  15. Sslcontext CTX = sslcontext.getinstance ("TLS");
  16. X509trustmanager TM = New X509trustmanager () {
  17. @Override
  18. public void checkclienttrusted (x509certificate[] chain,
  19. String authtype) throws certificateexception {
  20. }
  21. @Override
  22. public void checkservertrusted (x509certificate[] chain,
  23. String authtype) throws certificateexception {
  24. }
  25. @Override
  26. Public x509certificate[] Getacceptedissuers () {
  27. return null;
  28. }
  29. };
  30. Ctx.init (null, new TRUSTMANAGER[]{TM}, null);
  31. Sslsocketfactory SSF = new Sslsocketfactory (Ctx,sslsocketfactory.allow_all_hostname_verifier);
  32. Clientconnectionmanager CCM = This.getconnectionmanager ();
  33. schemeregistry sr = Ccm.getschemeregistry ();
  34. Sr.register (new Scheme ("https", 443, SSF));
  35. }
  36. }

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

[Java]View PlainCopy 
  1. Import java.util.ArrayList;
  2. Import Java.util.Iterator;
  3. Import java.util.List;
  4. Import Java.util.Map;
  5. Import Java.util.Map.Entry;
  6. Import org.apache.http.HttpEntity;
  7. Import Org.apache.http.HttpResponse;
  8. Import Org.apache.http.NameValuePair;
  9. Import org.apache.http.client.HttpClient;
  10. Import org.apache.http.client.entity.UrlEncodedFormEntity;
  11. Import Org.apache.http.client.methods.HttpPost;
  12. Import Org.apache.http.message.BasicNameValuePair;
  13. Import Org.apache.http.util.EntityUtils;
  14. /*
  15. * Tool class for Post requests with httpclient
  16. */
  17. Public class Httpclientutil {
  18. Public string DoPost (String url,map<string,string> map,string charset) {
  19. HttpClient HttpClient = null;
  20. HttpPost httppost = null;
  21. String result = null;
  22. try{
  23. HttpClient = new Sslclient ();
  24. HttpPost = new HttpPost (URL);
  25. //Set parameters
  26. list<namevaluepair> list = new arraylist<namevaluepair> ();
  27. Iterator Iterator = Map.entryset (). Iterator ();
  28. While (Iterator.hasnext ()) {
  29. entry<string,string> Elem = (entry<string, string>) Iterator.next ();
  30. List.add (New Basicnamevaluepair (Elem.getkey (), Elem.getvalue ()));
  31. }
  32. if (list.size () > 0) {
  33. urlencodedformentity entity = new urlencodedformentity (List,charset);
  34. Httppost.setentity (entity);
  35. }
  36. HttpResponse response = Httpclient.execute (HttpPost);
  37. if (response! = null) {
  38. Httpentity resentity = response.getentity ();
  39. if (resentity! = null) {
  40. result = Entityutils.tostring (Resentity,charset);
  41. }
  42. }
  43. }catch (Exception ex) {
  44. Ex.printstacktrace ();
  45. }
  46. return result;
  47. }
  48. }
3. Call the test code for the POST request

[Java]View PlainCopy 
  1. Import Java.util.HashMap;
  2. Import Java.util.Map;
  3. Testing the interface
  4. Public class Testmain {
  5. private String URL = "https://192.168.1.101/";
  6. private String charset = "Utf-8";
  7. private Httpclientutil httpclientutil = null;
  8. Public Testmain () {
  9. Httpclientutil = new Httpclientutil ();
  10. }
  11. public Void Test () {
  12. String httporgcreatetest = URL + "httporg/create";
  13. map<string,string> Createmap = new hashmap<string,string> ();
  14. Createmap.put ("Authuser","* * * * *");
  15. Createmap.put ("Authpass","* * * * *");
  16. Createmap.put ("Orgkey","* * *");
  17. Createmap.put ("OrgName","* * *");
  18. String Httporgcreatetestrtn = Httpclientutil.dopost (Httporgcreatetest,createmap,charset);
  19. System.out.println ("Result:" +httporgcreatetestrtn);
  20. }
  21. public static void Main (string[] args) {
  22. Testmain main = new Testmain ();
  23. Main.test ();
  24. }
  25. }

httpClient4.2 jar Package Download path: http://download.csdn.net/detail/hqmryang/4582440#comment

Java uses httpclient for post requests (HTTPS)

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.