【问题标题】:REST Android method not allowed on GET methodGET 方法上不允许使用 REST Android 方法
【发布时间】:2015-06-05 12:06:10
【问题描述】:

我有一个使用 Spring Tool Suite 制作的 android 应用程序和 REST 服务器。 REST 正在连接到数据库并根据 GET 请求中的查询返回 Json 对象列表。 这是我对 GET 方法的 REST 响应

@RequestMapping(value = "/short", method = RequestMethod.GET)
public  Map<String,List<Temperature>> shortPeriod(@RequestParam(value = "time",required = false)
         @DateTimeFormat(pattern="yyyy:MM:dd HH:mm:ss")  Date time){
    Map<String, List<Temperature>> results = new HashMap<String, List<Temperature>>();
    List<Temperature> temperatureList = new ArrayList<Temperature>();   
    System.out.println("TEST!");
    try {
        temperatureList = dataServices.getEntityList(time,"short");
        results.put("data", temperatureList);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return results;
}

这就是我在安卓上的连接方式

       String tempUrl = new String("http://" + IP + ":8080/" + "RestServer/temperature/" + tableName + "?time=" + urlQueryTimestamp);

        String encodedUrlTemp = tempUrl.replace(" ", "%20");
        String encodedUrl = encodedUrlTemp.replace("-", ":");

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();

我已经进行了测试打印,在 connection.connect() 之前它工作正常;

网址看起来像这样

http://192.168.1.106:8080/RestServer/temperature/short?time=2015:06:05%2010:20:03

我在连接之前打印“url”变量,当我将该 url 粘贴到 chrome 中时,我得到了正常的响应。但是当我尝试在我的应用程序中连接时,我得到“方法不允许”。我找到了一些关于该异常的解决方案,它通常是服务器上未实现的 POST 方法的问题,但是使用相同的 url,我在计算机上的 chrome 甚至在智能手机上的移动 chrome 上得到正常响应。 另一件事是我有另一台带有硬编码json数据的服务器进行测试,当http请求中没有查询时我可以正常连接,所以只有这个 http://192.168.1.106:8080/RestServer/temperature/short

所以我的假设是 chrome 在使用查询时会在内部转义一些字符串或自行设置一些标题信息,而 android 不会。服务器甚至没有记录我在上面的代码中粘贴的请求,就像我发送了错误的 url。

另一件事,我尝试使用 android 库中的 url 编码器,但它转义了一些不应该转义的字母,我读到它为 html 转义它,所以我正在手动进行(也许我正在这样做)错误的)。

我关掉了防火墙,查了十几次ip地址,我没有更多的想法。

【问题讨论】:

  • 先尝试不使用您的时间戳,我遇到了一个问题,由于时间戳中的非法字符,我从服务器收到 400 错误,如果是这种情况,请确保您完全对您的发送前的请求字符串。 - 附带说明一下 GSON 和 OkHttpClient 包,它们使这样的事情变得更容易:-)
  • @dave 感谢您的回复。我试过没有时间戳并且它正在工作,所以我很确定它是查询中的编码问题。我已经在使用 Gson,如果有帮助,我会看看 OkHttp,但如果我找不到任何其他解决方案,我可能会以毫秒为单位发送时间戳并在 android 和服务器上转换它

标签: java android json rest


【解决方案1】:

在尝试了我通过转义、更改库和阅读有关 URI 和 URL 找到的所有解决方案之后,我在 android 开发人员文档页面上找到了解决方案,上面写着:

HttpURLConnection 默认使用 GET 方法。 它将使用 POST 如果 setDoOutput(true) 已被调用。其他 HTTP 方法(OPTIONS、HEAD、 PUT、DELETE 和 TRACE) 可以与 setRequestMethod(String) 一起使用。

希望这对某人有所帮助

【讨论】:

    猜你喜欢
    • 2016-01-31
    • 1970-01-01
    • 2013-03-23
    • 2020-07-26
    • 2019-06-27
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多