【问题标题】:POST Requests from a Servlet来自 Servlet 的 POST 请求
【发布时间】: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


【解决方案1】:

您的本地主机将您的本地主机 IP 作为发送 IP。 Openshift et al 将 Openshift et al IP 作为发送 IP。因此,Google API 会说“我以前只见过两次 localhost IP,这很好!”,而它说“我以前见过这个 Openshift IP 数百万次!没有回复你!”

【讨论】:

  • 但是用我的API密钥,谷歌肯定没见过openshift IP百万次。您是否建议没有解决方法?
  • 如果服务显示“超出每日限制”,那么无论 API 密钥如何,显然它都不会再提供该 IP。 403 也可能意味着禁止,这只是意味着谷歌地理定位 API 根本不会以任何方式提供该服务。所以是的,我担心您可能没有解决方案。然而,可能对你有帮助的是:developers.google.com/maps/documentation/geocoding
  • 好吧,即使是这样,为什么它不在屏幕上打印错误?在 localhost 中,我尝试使用无效的密钥来执行此操作,它会在屏幕上打印谷歌的响应,同样的事情不会在开放班次中发生。
猜你喜欢
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 2016-03-19
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多