示範get、post請求如何算sn,算得sn如何使用

來源:互聯網
上載者: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. //需要httpclient-x.x.jar,httpcore-x.x.jar,commons-logging-x.x.jar,commons-httpclient-x.x.jar,commons-codec-x.x.jar包發http請求
  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.          * 以http://api.map.baidu.com/geocoder/v2/?address=百度大廈&output=json&ak=yourak為例
  32.          * ak設定了sn校正不能直接使用必須在url最後附上sn值,get請求計算sn跟url中參數對出現順序有關,需按序填充paramsMap,
  33.          * post請求是按字母序填充,具體參照testPost()
  34.          */
  35.         Map paramsMap = new LinkedHashMap<String, String>();
  36.         paramsMap.put("address", "百度大廈");
  37.         paramsMap.put("output", "json");
  38.         paramsMap.put("ak", "yourak");
  39.         // 調用下面的toQueryString方法,對paramsMap內所有value作utf8編碼
  40.         String paramsStr = toQueryString(paramsMap);
  41.         // 對paramsStr前面拼接上/geocoder/v2/?,後面直接拼接yoursk
  42.         String wholeStr = new String("/geocoder/v2/?" + paramsStr + "yoursk");
  43.         // 對上面wholeStr再作utf8編碼
  44.         String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
  45.         // 調用下面的MD5方法得到sn簽名值
  46.         String sn = MD5(tempStr);
  47.         // 算得sn後發送get請求
  48.         HttpClient client = new DefaultHttpClient();
  49.         HttpGet httpget = new HttpGet(
  50.                 "http://api.map.baidu.com/geocoder/v2/?address=百度大廈&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.         // 列印響應內容
  56.         System.out.println(result);
  57.     }
  58.     public void testPost() throws Exception {
  59.         /**
  60.          * 以http://api.map.baidu.com/geodata/v3/geotable/create建立表為例
  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.         // post請求是按字母序填充,對上面的paramsMap按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.         // 調用下面的MD5方法得到sn簽名值
  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.         // 列印響應內容
  90.         System.out.println(result);
  91.     }
  92.     // 對Map內所有value作utf8編碼,拼接返回結果
  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計算方法,調用了MessageDigest庫函數,並把byte數組結果轉換成16進位
  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.     // 將輸入資料流轉換成字串
  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. }

示範get、post請求如何算sn,算得sn如何使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.