api.location.BaiduPlaceAPI.java Source code

Java tutorial

Introduction

Here is the source code for api.location.BaiduPlaceAPI.java

Source

/**
 * @author williamz 201495
 *
 * Copyright (c) 2013, Synnex and/or its affiliates. All rights reserved.
 * SYNNEX PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package api.location;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaiduPlaceAPI {

    private URL url;
    private HttpURLConnection httpURLConn;

    public void myDoGet() {
        try {
            url = new URL(createUrlString());
            httpURLConn = (HttpURLConnection) url.openConnection();
            httpURLConn.setDoOutput(true);
            httpURLConn.setRequestMethod("GET");
            httpURLConn.connect();
            InputStream in = httpURLConn.getInputStream();
            List<String> lines = IOUtils.readLines(in, "UTF-8");
            StringBuilder sb = new StringBuilder();
            for (String line : lines) {
                System.out.println(line);
                sb.append(line);
            }
            Response parsed = JSONObject.parseObject(sb.toString(), Response.class);
            System.out.println(parsed);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpURLConn != null) {
                httpURLConn.disconnect();
            }
        }
    }

    private String createUrlString() throws UnsupportedEncodingException {
        String baseUrl = "http://api.map.baidu.com/place/v2/search?ak=2d33ba4d2ab64e03723feb96caa13c57";

        Map<String, String> params = new HashMap<>();
        params.put("query", URLEncoder.encode("", "UTF-8"));
        params.put("tag", URLEncoder.encode("?", "UTF-8"));
        params.put("region", URLEncoder.encode("?", "UTF-8"));
        params.put("output", "json");

        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            sb.append("&" + key + "=" + params.get(key));
        }

        return baseUrl + sb.toString();
    }

    public static void main(String[] args) {
        BaiduPlaceAPI hg = new BaiduPlaceAPI();
        hg.myDoGet();
    }

}