標籤:
- import java.io.ByteArrayOutputStream;
- import java.io.InputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.URLEncoder;
- import java.util.ArrayList;
- import java.util.LinkedHashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.TreeMap;
- //需要httpclient-x.x.jar,httpcore-x.x.jar,commons-logging-x.x.jar,commons-httpclient-x.x.jar,commons-codec-x.x.jar包發http請求
- import org.apache.commons.httpclient.URIException;
- import org.apache.commons.httpclient.util.URIUtil;
- 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.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicNameValuePair;
- public class SnTest {
- public static void main(String[] args) throws Exception {
- SnTest snTest = new SnTest();
- snTest.testGet();
- snTest.testPost();
- }
- public void testGet() throws Exception {
- /**
- * 以http://api.map.baidu.com/geocoder/v2/?address=百度大廈&output=json&ak=yourak為例
- * ak設定了sn校正不能直接使用必須在url最後附上sn值,get請求計算sn跟url中參數對出現順序有關,需按序填充paramsMap,
- * post請求是按字母序填充,具體參照testPost()
- */
- Map paramsMap = new LinkedHashMap<String, String>();
- paramsMap.put("address", "百度大廈");
- paramsMap.put("output", "json");
- paramsMap.put("ak", "yourak");
- // 調用下面的toQueryString方法,對paramsMap內所有value作utf8編碼
- String paramsStr = toQueryString(paramsMap);
- // 對paramsStr前面拼接上/geocoder/v2/?,後面直接拼接yoursk
- String wholeStr = new String("/geocoder/v2/?" + paramsStr + "yoursk");
- // 對上面wholeStr再作utf8編碼
- String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
- // 調用下面的MD5方法得到sn簽名值
- String sn = MD5(tempStr);
- // 算得sn後發送get請求
- HttpClient client = new DefaultHttpClient();
- HttpGet httpget = new HttpGet(
- "http://api.map.baidu.com/geocoder/v2/?address=百度大廈&output=json&ak=yourak&sn="
- + sn);
- HttpResponse response = client.execute(httpget);
- InputStream is = response.getEntity().getContent();
- String result = inStream2String(is);
- // 列印響應內容
- System.out.println(result);
- }
- public void testPost() throws Exception {
- /**
- * 以http://api.map.baidu.com/geodata/v3/geotable/create建立表為例
- */
- LinkedHashMap<String, String> paramsMap = new LinkedHashMap<String, String>();
- paramsMap.put("geotype", "1");
- paramsMap.put("ak", "yourak");
- paramsMap.put("name", "geotable80");
- paramsMap.put("is_published", "1");
- // post請求是按字母序填充,對上面的paramsMap按key的字母序排列
- Map<String, String> treeMap = new TreeMap<String, String>(paramsMap);
- String paramsStr = toQueryString(treeMap);
- String wholeStr = new String("/geodata/v3/geotable/create?" + paramsStr
- + "yoursk");
- String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
- // 調用下面的MD5方法得到sn簽名值
- String sn = MD5(tempStr);
- HttpClient client = new DefaultHttpClient();
- HttpPost post = new HttpPost(
- "http://api.map.baidu.com/geodata/v3/geotable/create");
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("geotype", "1"));
- params.add(new BasicNameValuePair("ak", "yourak"));
- params.add(new BasicNameValuePair("name", "geotable80"));
- params.add(new BasicNameValuePair("is_published", "1"));
- params.add(new BasicNameValuePair("sn", sn));
- HttpEntity formEntity = new UrlEncodedFormEntity(params);
- post.setEntity(formEntity);
- HttpResponse response = client.execute(post);
- InputStream is = response.getEntity().getContent();
- String result = inStream2String(is);
- // 列印響應內容
- System.out.println(result);
- }
- // 對Map內所有value作utf8編碼,拼接返回結果
- public String toQueryString(Map<?, ?> data)
- throws UnsupportedEncodingException, URIException {
- StringBuffer queryString = new StringBuffer();
- for (Entry<?, ?> pair : data.entrySet()) {
- queryString.append(pair.getKey() + "=");
- // queryString.append(URLEncoder.encode((String) pair.getValue(),
- // "UTF-8") + "&");
- queryString.append(URIUtil.encodeQuery((String) pair.getValue(),
- "UTF-8") + "&");
- }
- if (queryString.length() > 0) {
- queryString.deleteCharAt(queryString.length() - 1);
- }
- return queryString.toString();
- }
- // MD5計算方法,調用了MessageDigest庫函數,並把byte數組結果轉換成16進位
- public String MD5(String md5) {
- try {
- java.security.MessageDigest md = java.security.MessageDigest
- .getInstance("MD5");
- byte[] array = md.digest(md5.getBytes());
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < array.length; ++i) {
- sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
- .substring(1, 3));
- }
- return sb.toString();
- } catch (java.security.NoSuchAlgorithmException e) {
- }
- return null;
- }
- // 將輸入資料流轉換成字串
- private static String inStream2String(InputStream is) throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buf = new byte[1024];
- int len = -1;
- while ((len = is.read(buf)) != -1) {
- baos.write(buf, 0, len);
- }
- return new String(baos.toByteArray(), "UTF-8");
- }
- }
示範get、post請求如何算sn,算得sn如何使用