【问题标题】:Sending request to Spring framework(MVC) using Get method in volley in Android在 Android 的 volley 中使用 Get 方法向 Spring 框架(MVC)发送请求
【发布时间】:2018-06-06 13:52:10
【问题描述】:

我想知道是否可以在android中使用volley从spring框架(spring mvc)发送和接收请求。 因为我相信也有 spring for android 之类的东西,但是是否有必要使用它,或者我们可以单独使用 spring 制作服务器并使用它的 URL(http://localhost:8080/...etc.) 像往常一样获得响应。

【问题讨论】:

    标签: android spring spring-mvc networking android-volley


    【解决方案1】:

    您可以使用 spring mvc 构建 restful api。检查this guide to build restful api

    【讨论】:

      【解决方案2】:

      在您的app/build.gradle 上输入以下代码:

      dependencies {
          ...
          implementation 'com.android.volley:volley:1.1.0'
          ...
      }
      

      您的通话请求必须与此类似:

      RequestQueue queue = Volley.newRequestQueue(this);
      JsonRequest request = new JsonObjectRequest("http://localhost:8080/...etc",
              null, //if jsonRequest == null then Method.GET otherwise Method.POST
              new Response.Listener<JSONObject>() {
          @Override
          public void onResponse(JSONObject response) {
              //handler the response here
          }
      }, new Response.ErrorListener() {
          @Override
          public void onErrorResponse(VolleyError error) {
              //handler the error here
          }
      });
      queue.add(request);
      

      【讨论】:

      • 我已经为 volley(Json object Request) 编写了完美的代码,因为它可以与除我使用 spring 框架 (MVC) 制作的 URL 之外的其他 URL 一起使用。它总是说连接被拒绝是错误原因,我已经摆脱了任何类型的防火墙和代理问题
      • 一个不错的选择是Retrofit。我的后卫兄弟
      【解决方案3】:

      经过长时间的编码和实现各种想法,好吧。

      事实证明这没什么大不了的。

      问题是,由于我的 spring 框架(MVC)服务器是本地的 主机基本上没有托管)因此,它不能由其他设备通过公共互联网访问。

      即假设我在我的电脑上启动了我的 Spring MVC(apache tomcat 服务器), 如果我在模拟器中运行该应用程序,那么该应用程序只能向/从服务器发送和接收请求(因为它在同一设备 - 我的电脑上运行)。

      简单地说-我认为您可能需要与 pc(您所在的位置)相同的 IP 地址运行您的服务器)以使其在未托管站点的情况下工作。暗示,在模拟器上运行它,因为它可以在同一设备上运行。

      注意

      当使用 volley 或任何其他方法(Async Task..etc.)并在模拟器上运行应用程序时 - 在您的 URL 字符串中使用 10.0.2.2 而不是 localhost

      原因

      它是主机环回接口的特殊别名,即 127.0.0.1,它通常又映射到主机名-localhost

      回送设备是一种特殊的虚拟网络接口,您的计算机使用它来与自身通信。它主要用于诊断和故障排除,以及连接到本地计算机上运行的服务器。

      希望对您有所帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-20
        • 1970-01-01
        • 2020-12-07
        相关资源
        最近更新 更多