发布Google Maps API v2 Android的流媒体路线

因此,我的应用程序的一部分构建导航方向字符串,然后尝试解析JSON并在我的地图上绘制折线路线.我首先使用Location变量或Locale常量构建我的字符串.我最终得到了类似的东西

https://maps.googleapis.com/maps/api/directions/json?origin=Full Frame Documentary Film 
Festival, Durham, 27701&destination=601 W Peace St, Raleigh,27605&sensor=false&key={API_KEY}

>没有新行(为了便于阅读,我添加了它),{API_KEY}是我的实际api键.

我遇到的问题是,当我将URL String传递给此downloadUrl(String urlString)方法时

private String downloadUrl(String urlString) throws IOException {
    Log.d(TAG, "Downloaded string = " + urlString);
    String data = "";
    InputStream stream = null;
    HttpURLConnection urlConnection = null;
    try {

        // Display our JSON in our browser (to show us how we need to implement our parser)
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(urlString)); 
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

        URL url = new URL(urlString);

        // Create a http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();

        // read in our data
        stream = urlConnection.getInputStream(); 
        BufferedReader br = new BufferedReader(new InputStreamReader(stream)); 
        StringBuffer sb = new StringBuffer();   

        // read in our data in, and append it as a single data string
        String line = "";
        while ((line = br.readLine()) != null) {
            Log.d(TAG,"url download stream: " + line);
            sb.append(line);
        }
        data = sb.toString();
        br.close();
    } 
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        Log.d(TAG, "Downloaded data = " + data);
        stream.close();
        urlConnection.disconnect();
    }

    return data;
}    

JSON正确显示在我的浏览器中,我看到了Google在文档中描述的所有内容.但是当我尝试打开与URL的连接并将JSON拉入字符串进行解析时,在以下行中,我得到了System.err通知

05-02 09:56:01.540: W/System.err(32232): java.io.FileNotFoundException: 
https://maps.googleapis.com/maps/api/directions/json?origin=Full Frame Documentary 
Film Festival, Durham, 27701&destination=601 W Peace St, Raleigh, 27605&sensor=false&key={API_KEY}

我想我的困惑在于浏览器完美地显示解析的地址,但是然后连接到(我相信的)同一服务器返回FNFE.假设是这种情况我错了吗?如果是这样,我的钥匙可能是错的?令人困惑的是,此代码适用于其他应用程序.

解决方法:

你必须对params进行URL编码,例如: URL中的空格(“”)写为“”.您的浏览器在内部执行此操作,可能没有向您显示提交的URL.

static String urlEncode(String value) {
    try {
        return URLEncoder.encode(value, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return value;
    }
}

但是不要编码整个URL,只编码参数值.如果参数名称是非ASCII,则必须对它们进行编码,但Google API不使用此类参数.

上一篇:java – Android HttpURLConnection PUT到亚马逊AWS S3 403错误


下一篇:在java程序中使用浏览器的证书