演示get、post请求如何算sn,算得sn如何使用

  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. }
posted @ 2015-07-14 12:15  _1900  阅读(817)  评论(0编辑  收藏  举报