【问题标题】:How to do GET API Request with URL params?如何使用 URL 参数进行 GET API 请求?
【发布时间】:2017-12-05 09:50:32
【问题描述】:
Client client = ClientBuilder.newClient();
urlApi="https://localhost:123/demo/api/v1/rows/search?";
WebTarget webTarget = client.target(urlApi);
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
    webTarget.queryParam(entry.getKey(), entry.getValue());
}
webTarget.queryParam("searchConditions",webTarget.queryParam("mobileNo","+9999999999"));

Invocation.Builder builder = webTarget.request();

builder.header("id", "ABC");
String asB64 = Base64.getEncoder().encodeToString("ABC:PWD".getBytes("utf-8"));
logger.debug("Calling  API "+urlApi);
builder.header("Authorization", "Basic "+asB64);
builder.header("Content-type", MediaType.APPLICATION_JSON);     
response = builder.get();
responseData = response.readEntity(String.class);
System.out.println(responseData);

我正在尝试使用 searchCondition 作为键和值作为 {mobileNo="+919999999999"} 的 GET 请求,但我无法让它工作。

除此之外,我如何打印请求“标题”以及“查询参数”?提前谢谢你

【问题讨论】:

    标签: java rest get query-parameters


    【解决方案1】:

    我认为您需要对值输入进行编码,如下所示:

    webTarget.queryParam("searchCondition", URLEncoder.encode("{mobileNo=\"+919999999999\"}", StandardCharsets.UTF_8.toString()));
    

    UDPATE: 使用 Spring 的其余客户端示例:

    @Test
    public void testStack() throws Exception {
        RestTemplate rest = new RestTemplate();
        String fooResourceUrl="http://localhost:8080/usersParam?";
        RestTemplate restTemplate = new RestTemplate();
        String parameter = "{mobileNo=\"+919999999999\"}";
    
        ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "parameter=" + URLEncoder.encode(parameter, StandardCharsets.UTF_8.toString() ), String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    }
    

    这将是其余的服务:

    @RequestMapping(method = RequestMethod.GET, value="/usersParam")
        public User getUsersInfo(@RequestParam String parameter) throws UnsupportedEncodingException {
             System.out.println(URLDecoder.decode(parameter, StandardCharsets.UTF_8.toString() ));
            return null;
        }
    

    【讨论】:

    • 它仍然无法正常工作。 localhost:123/demo/api/v1/rows/search?searchConditions={mobileNo=+919899999999} 这适用于邮递员...
    • 查看更新的回复。我已经完成了一项服务(userParams)并请求了一个参数(您的 searchConditions)。唯一的问题是服务器也要解码参数值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 2019-10-01
    相关资源
    最近更新 更多