java - 使用 Java 向 Google Elevation API 发送请求

标签 java google-maps-api-3 google-api

我尝试向 Google 海拔 API 发送 Post 请求并期待响应

private final String ELEVATION_API_URL =  "https://maps.googleapis.com/maps/api/elevation/json";

private final String USER_AGENT = "Mozilla/5.0";

String urlParameters = "locations=6.9366681,79.9393521&sensor=true&key=<API KEY>";


URL obj = new URL(ELEVATION_API_URL);
            java.net.HttpURLConnection con = (java.net.HttpURLConnection)obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", USER_AGENT);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("Content-Language", "en-US");  

            String urlParameters = request;

            // Send post request
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();

我以这种方式发送请求,但我收到的响应代码为 400。当从浏览器发送请求时,这是有效的。这段代码有什么问题。

最佳答案

为了让我取回 XML,我对您的项目进行了以下更改

StringBuilder response = new StringBuilder(); // placed on the top of your Class

**wr.writeBytes(urlParameters.toString());** // as you have it in your code
System.out.println("ResponseMessage : " + connection.getResponseMessage());
System.out.println("RequestMethod : " + connection.getRequestMethod());

in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String inputLine;

while ((inputLine = in.readLine()) != null) {

    response.append(inputLine);

}

in.close();

wr.flush();

wr.close();

//我将 URL 更改为:
私有(private)最终字符串 ELEVATION_API_URL = "https://maps.googleapis.com/maps/api/elevation/xml ";

//**I get XML in the response** 

return response.toString();

关于java - 使用 Java 向 Google Elevation API 发送请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22790261/

相关文章:

javascript - Google map 热图和标记

javascript - Google Maps API 多边形内的蜿蜒路径,带有旋转/增长/收缩/排序选项

java - JasperReports 是在 Web 应用程序中显示报告的适当解决方案吗?

java - 使用反射加载类时避免 ClassNotFoundException

mysql - 哪个 FOSS RDBMS 用于地理空间数据?

oauth - 在初始身份验证后执行 Google 联合登录/oAuth2

node.js - 使用 API 创建 Google 日历事件不会创建环聊链接

java - 如何使用 Java 从网站检索 URL?

java - 运行 Jar 时的当前工作目录

go - 无法使用默认服务帐户和谷歌云库从谷歌 Kubernetes 引擎访问谷歌云存储