我正在使用eclipse编写一个servlet,它接收来自客户端的POST请求,该请求应该对收到的文本进行一些拆分,访问Google地理位置api以获取一些数据并显示给用户。来自Servlet的POST请求
在本地主机上,这工作得很好。在实际的服务器上(使用Openshift和CloudBees尝试),这不起作用。我可以看到分裂的回复,但不是来自Google地理位置服务的回复。总是有一个错误从Google服务登录到控制台。但是,相同的代码在localhost上工作得很好。
后,我收到在servlet的doPost
方法POST请求,我做了以下访问谷歌地理位置服务:
//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,这意味着每日限制超越..但如果我在本地执行相同的东西,它的工作原理很好...... –