0

当我使用我的应用程序发送以下 URL 时,我遇到了以下错误:

服务器返回 HTTP 响应代码:400 用于 URL:http : //maps.googleapis.com/maps/api/distancematrix/xml?origins=Medical Centre+ 308 George Street+ Sydney&destinations= Science Museum Exhibition Road London SW7 2DD&mode=driving&sensor=false

但是通过在浏览器中输入 URL 会发现它是正确的!

4

2 回答 2

1

在获取它之前,您可能需要对 url 进行 urlencode。看一下查询字符串参数的Java URL编码

于 2012-10-05T04:48:24.567 回答
1

您可以在打开连接以读取数据之前对请求 URL 进行编码。请查看以下代码以更好地理解:

package com.stackoverflow.works;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;

public class URLReader {
    /*
     * @author: sarath_sivan
     */

    public static void read(String url) throws IOException {
        setProxy();//only invoke this method if you are using any proxy to open connection
        URL httpURL = new URL(url);
        BufferedReader bufferedReader = new BufferedReader(
        new InputStreamReader(httpURL.openStream()));

        String inputLine;
        while ((inputLine = bufferedReader.readLine()) != null) {
            System.out.println(inputLine);
        }   
        bufferedReader.close();
    }

    public static void setProxy() {
        System.getProperties().put("http.proxyHost", "xxx.xxx.xx.xx");//replace with your proxy
        System.getProperties().put("http.proxyPort", "8080");
    }

    public static String encodeURL(String url) throws UnsupportedEncodingException {//encoding your request url parameters here
        StringBuilder encodedURL = new StringBuilder(url);
        encodedURL.append("?origins=").append(encode("Medical Centre+ 308 George Street+ Sydney"));
        encodedURL.append("&destinations=").append(encode(" Science Museum Exhibition Road London SW7 2DD"));
        encodedURL.append("&mode=").append("driving");
        encodedURL.append("&sensor=").append("false");
        return encodedURL.toString();
    }

    public static String encode(String string) throws UnsupportedEncodingException {
        return URLEncoder.encode(string, "ISO-8859-1");
    }

    public static void main(String[] args) throws IOException {
        String url = "http://maps.googleapis.com/maps/api/distancematrix/xml";
        read(encodeURL(url));
    }

}

输出如下所示: 在此处输入图像描述

于 2012-10-05T06:18:27.727 回答