开发入门示例

下面将通过一段简单的java示例来解释如何调用大众点评开发者的API:


Step 1: 获取App Key和App Secret
请登录开发者平台(尚未注册?请点击这里),进入“管理中心”,确认自己的App Key和App Secret。

	String appKey = "5589931241";
	String secret = "db16adf193f2448ba0ec0260e0c968f3";
	//请替换为自己的 App Key 和 App secret

Step 2: 确认请求参数
查看API文档,确认请求参数。

	String apiUrl = "http://api.dianping.com/v1/business/find_businesses";
	paramMap.put("city", "上海");
	paramMap.put("latitude", "31.21524");
	paramMap.put("longitude", "121.420033");
	paramMap.put("category", "美食");
	paramMap.put("region", "长宁区");
	paramMap.put("limit", "20");
	paramMap.put("radius", "2000");
	paramMap.put("offset_type", "0");
	paramMap.put("has_coupon", "1");
	paramMap.put("has_deal", "1");
	paramMap.put("keyword", "泰国菜");
	paramMap.put("sort", "7");
	paramMap.put("format", "json");

Step 3: 生成请求签名
调用点评API需要生成加密的请求签名,以防止API被盗用。开发者需要根据请求参数、App Key、App Secret生成签名, 注意这里使用Apache-Codec进行SHA1签名,其他语言的签名请参考SDK。 示例包括:

Java           iOS           PHP         C#

javascript       Android       Python       微信SDK

详细请参照请求签名生成文档

	 StringBuilder stringBuilder = new StringBuilder();

	// 对参数名进行字典排序
	String[] keyArray = paramMap.keySet().toArray(new String[0]);
	Arrays.sort(keyArray);
	// 拼接有序的参数名-值串
	stringBuilder.append(appKey);
	for (String key : keyArray)
	{
	    stringBuilder.append(key).append(paramMap.get(key));
	}
	String codes = stringBuilder.append(secret).toString();
	String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes).toUpperCase();

Step 4: 拼接请求URL
App Key、参数、生成的签名(即sign)以及API的访问路径(即apiUrl)拼接成一个URL

	// 添加签名
	stringBuilder = new StringBuilder();
	stringBuilder.append("appkey=").append(appKey).append("&sign=").append(sign);
	for (Entry≶String, String> entry : paramMap.entrySet())
	{
	    stringBuilder.append('&').append(entry.getKey()).append('=').append(entry.getValue());
	}
	String queryString = stringBuilder.toString();

Step 5: 发起请求并获得返回结果
根据API的属性,采用HTTP请求向服务器发起请求(目前所有API都使用GET方式获取数据)并获取响应结果。这里使用Apache-HttpClient,注意请求之前需要将请求参数进行UTF-8编码

	StringBuffer response = new StringBuffer();
	HttpClientParams httpConnectionParams = new HttpClientParams();
	httpConnectionParams.setConnectionManagerTimeout(1000);
	HttpClient client = new HttpClient(httpConnectionParams);
	HttpMethod method = new GetMethod(apiUrl);

	BufferedReader reader = null;
	String encodeQuery = URIUtil.encodeQuery(queryString, "UTF-8"); // UTF-8 请求
	method.setQueryString(encodeQuery);
	client.executeMethod(method);
	reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
	String line = null;
	while ((line = reader.readLine()) != null)
	{
	    response.append(line).append(System.getProperty("line.separator"));
	}
	reader.close();
	method.releaseConnection();
	System.out.println(response.toString());
	
完整代码请点击这里下载