【发布时间】:2023-03-28 00:07:01
【问题描述】:
我正在使用 eclipse 编写一个 servlet,它接收来自客户端的 POST 请求,该请求应该对收到的文本进行一些拆分,访问 google geolocation api 以获取一些数据并显示给用户。
在本地主机上,这工作得很好。在实际服务器上(尝试使用 Openshift 和 CloudBees),这不起作用。我可以看到拆分回复,但看不到来自谷歌地理定位服务的回复。总是有一个错误从谷歌服务登录到控制台。但是,相同的代码在 localhost 上运行得非常好。
在 servlet 的 doPost 方法中收到 POST 请求后,我正在执行以下操作以访问 Google GeoLocation 服务:
//Attempting to send data to Google Geolocation Service
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL("https://www.googleapis.com/geolocation/v1/geolocate?key=MyAPI");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request with data (output variable has the JSON data)
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (output);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response2 = new StringBuffer();
while((line = rd.readLine()) != null) {
response2.append(line);
response2.append('\r');
}
rd.close();
//Write to Screen using out=response.getWriter();
out.println("Access Point's Location = " + response2.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
你能告诉我为什么会这样吗?我怎样才能做到这一点?我应该求助于 AJAX 之类的东西还是有其他解决方法?我对编码比较陌生,因此在这个阶段尽量避免学习 AJAX。如果有其他方法可以让这个工作,请告诉我
【问题讨论】:
-
它不起作用。 有点模糊。 “我可以看到拆分回复,但看不到来自谷歌地理定位服务的回复。”这是否意味着请求被超时取消了?
-
我相信它超时了。日志显示 Google 错误 403,这意味着超出每日限制..但是如果我在 localhost 上执行相同的操作,它就可以正常工作...
标签: java ajax eclipse servlets openshift