Demonstrates how a get, POST request is SN, and how SN is used

Source: Internet
Author: User

  1. Import Java.io.ByteArrayOutputStream;
  2. Import Java.io.InputStream;
  3. Import java.io.UnsupportedEncodingException;
  4. Import Java.net.URLEncoder;
  5. Import java.util.ArrayList;
  6. Import Java.util.LinkedHashMap;
  7. Import java.util.List;
  8. Import Java.util.Map;
  9. Import Java.util.Map.Entry;
  10. Import Java.util.TreeMap;
  11. Requires Httpclient-x.x.jar,httpcore-x.x.jar,commons-logging-x.x.jar,commons-httpclient-x.x.jar,commons-codec-x.x.jar packet to send HTTP request
  12. Import org.apache.commons.httpclient.URIException;
  13. Import Org.apache.commons.httpclient.util.URIUtil;
  14. Import org.apache.http.HttpEntity;
  15. Import Org.apache.http.HttpResponse;
  16. Import Org.apache.http.NameValuePair;
  17. Import org.apache.http.client.HttpClient;
  18. Import org.apache.http.client.entity.UrlEncodedFormEntity;
  19. Import Org.apache.http.client.methods.HttpGet;
  20. Import Org.apache.http.client.methods.HttpPost;
  21. Import org.apache.http.impl.client.DefaultHttpClient;
  22. Import Org.apache.http.message.BasicNameValuePair;
  23. public class Sntest {
  24. public static void Main (string[] args) throws Exception {
  25. Sntest sntest = new Sntest ();
  26. Sntest.testget ();
  27. Sntest.testpost ();
  28. }
  29. public void Testget () throws Exception {
  30. /**
  31. * Take http://api.map.baidu.com/geocoder/v2/?address= Baidu mansion &output=json&ak=yourak as an example
  32. * AK Set SN Check cannot be used directly must be appended to the URL at the end of the SN value, GET request calculation sn and URL parameters in the order of occurrence, need to be ordered to populate the Paramsmap,
  33. * The POST request is populated alphabetically, with reference to Testpost ()
  34. */
  35. Map Paramsmap = new linkedhashmap<string, string> ();
  36. Paramsmap.put ("Address", "Baidu Building");
  37. Paramsmap.put ("Output", "json");
  38. Paramsmap.put ("AK", "Yourak");
  39. Call the following toquerystring method to encode all the value in Paramsmap UTF8
  40. String paramsstr = toquerystring (Paramsmap);
  41. Paramsstr front stitching on/geocoder/v2/?, behind the direct stitching Yoursk
  42. String wholestr = new String ("/geocoder/v2/?" + paramsstr + "Yoursk");
  43. UTF8 code for the above WHOLESTR
  44. String TempStr = Urlencoder.encode (Wholestr, "UTF-8");
  45. Call the following MD5 method to get the SN signature value
  46. String sn = MD5 (TEMPSTR);
  47. Send GET request after SN
  48. HttpClient client = new Defaulthttpclient ();
  49. HttpGet httpget = new HttpGet (
  50. "Http://api.map.baidu.com/geocoder/v2/?address= Baidu Building &output=json&ak=yourak&sn="
  51. + sn);
  52. HttpResponse response = Client.execute (HttpGet);
  53. InputStream is = Response.getentity (). getcontent ();
  54. String result = Instream2string (IS);
  55. Print response content
  56. SYSTEM.OUT.PRINTLN (result);
  57. }
  58. public void Testpost () throws Exception {
  59. /**
  60. * Take http://api.map.baidu.com/geodata/v3/geotable/create CREATE TABLE as an example
  61. */
  62. linkedhashmap<string, string> paramsmap = new linkedhashmap<string, string> ();
  63. Paramsmap.put ("Geotype", "1");
  64. Paramsmap.put ("AK", "Yourak");
  65. Paramsmap.put ("name", "Geotable80");
  66. Paramsmap.put ("is_published", "1");
  67. The POST request is populated alphabetically by alphabetical order of the above Paramsmap by key
  68. map<string, string> treeMap = new treemap<string, string> (PARAMSMAP);
  69. String paramsstr = toquerystring (TREEMAP);
  70. String wholestr = new String ("/geodata/v3/geotable/create?" + paramsstr
  71. + "Yoursk");
  72. String TempStr = Urlencoder.encode (Wholestr, "UTF-8");
  73. Call the following MD5 method to get the SN signature value
  74. String sn = MD5 (TEMPSTR);
  75. HttpClient client = new Defaulthttpclient ();
  76. HttpPost post = new HttpPost (
  77. "Http://api.map.baidu.com/geodata/v3/geotable/create");
  78. list<namevaluepair> params = new arraylist<namevaluepair> ();
  79. Params.add (New Basicnamevaluepair ("Geotype", "1"));
  80. Params.add (New Basicnamevaluepair ("AK", "Yourak"));
  81. Params.add (New Basicnamevaluepair ("name", "Geotable80"));
  82. Params.add (New Basicnamevaluepair ("is_published", "1"));
  83. Params.add (New Basicnamevaluepair ("SN", SN));
  84. Httpentity formentity = new urlencodedformentity (params);
  85. Post.setentity (formentity);
  86. HttpResponse response = Client.execute (POST);
  87. InputStream is = Response.getentity (). getcontent ();
  88. String result = Instream2string (IS);
  89. Print response content
  90. SYSTEM.OUT.PRINTLN (result);
  91. }
  92. UTF8 encode all the value in map, stitching back the result
  93. Public String toquerystring (map<?,? > Data)
  94. Throws Unsupportedencodingexception, Uriexception {
  95. StringBuffer queryString = new StringBuffer ();
  96. For (entry<?,? > Pair:data.entrySet ()) {
  97. Querystring.append (Pair.getkey () + "=");
  98. Querystring.append (Urlencoder.encode (String) Pair.getvalue (),
  99. "UTF-8") + "&");
  100. Querystring.append (Uriutil.encodequery (String) Pair.getvalue (),
  101. "UTF-8") + "&");
  102. }
  103. if (querystring.length () > 0) {
  104. Querystring.deletecharat (Querystring.length ()-1);
  105. }
  106. return querystring.tostring ();
  107. }
  108. MD5 calculation method, call the MessageDigest library function, and convert the result of byte array to 16 binary
  109. public string MD5 (string md5) {
  110. try {
  111. Java.security.MessageDigest MD = Java.security.MessageDigest
  112. . getinstance ("MD5");
  113. byte[] Array = md.digest (Md5.getbytes ());
  114. StringBuffer sb = new StringBuffer ();
  115. for (int i = 0; i < Array.Length; ++i) {
  116. Sb.append (integer.tohexstring (array[i & 0xFF) | 0x100)
  117. . substring (1, 3));
  118. }
  119. return sb.tostring ();
  120. } catch (Java.security.NoSuchAlgorithmException e) {
  121. }
  122. return null;
  123. }
  124. Convert input flow to string
  125. private static String instream2string (InputStream is) throws Exception {
  126. Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
  127. byte[] buf = new byte[1024];
  128. int len =-1;
  129. while (len = Is.read (BUF))! =-1) {
  130. Baos.write (buf, 0, Len);
  131. }
  132. return new String (Baos.tobytearray (), "UTF-8");
  133. }
  134. }

Shows how the GET, POST request is SN, and how SN is used

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.