我尝试向 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/