【问题标题】:How to pass '/' character in the GET request?如何在 GET 请求中传递 '/' 字符?
【发布时间】:2018-04-18 16:01:15
【问题描述】:

我有一个 api:

http://localhost:8080/mylocalserver/#/reports/{parameter1}/{parameter2}

现在第一个参数是 parameter1 = "12345/EF" 第二个参数是parameter2 = "Text"

我正在使用 Spring Rest Controller 来创建 api。 当使用以下上述参数发出请求时,它会显示 Request Not Found 错误。

我尝试使用URLEncoder.encodeUriUtils.encode(param, StandardCharsets.UTF_8.name()) 对参数进行编码和解码,但仍然出现相同的错误。

下面是我试过的代码。

假设我从用户输入中得到了两个变量 parameter1parameter2

现在我使用以下参数创建一个 URL

private void createApi(String parameter1, String parameter2) {
    try {
      String uri = " http://localhost:8080/mylocalserver/#/reports/"+encode(parameter1)+"/"+encode(parameter2)+" ";

      ServletRequestAttributes requestAttributes =
          (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
      HttpServletRequest request = requestAttributes.getRequest();
      HttpServletResponse response = requestAttributes.getResponse();
      request.getRequestDispatcher(uri).forward(request, response);
    } catch (Exception e) {
      LOG.error(e.getMessage(), e);
    }
  }

我的编码方法是:

public String encode(String param) {
    try {
     UriUtils.encode(param, StandardCharsets.UTF_8.name())
      }
    } catch (Exception e) {
      LOG.error(e.getMessage(), e);
    }
    return param;
  }

注意:我使用的是 Tomcat 8.5

【问题讨论】:

标签: java spring-restcontroller


【解决方案1】:

你的编码方法坏了:

缺少return 语句。

public String encode(String param) {
    try {
        //missing return at this line in your code
        return UriUtils.encode(param, StandardCharsets.UTF_8.name())
      }
    } catch (Exception e) {
      LOG.error(e.getMessage(), e);
    }
    return param;
  }

顺便说一句,您可以将此方法设为静态。

【讨论】:

  • 如果你修复了错误而不是仅仅指出它可能会更清楚。
  • 但是我已经完成了这个修复,因为它是我输入错误的。请提供比这个更好的方法
  • 然后显示你的真实代码 - 这个答案解决了你在问题中描述的问题(除了错误处理,但如果发现错误则返回原始字符串)......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-18
  • 2021-12-29
  • 1970-01-01
相关资源
最近更新 更多