【问题标题】:Java REST Client: print get request (json)?Java REST客户端:打印获取请求(json)?
【发布时间】:2018-02-22 08:25:40
【问题描述】:

我正在尝试将 Java 中 GET 请求的返回值打印到 Jira REST API,但它似乎对我不起作用。身份验证工作正常,但不知何故代码没有打印任何内容。

public class Test {

    public static void main(String[] args) {

    String user = "myusername";
    String password = "mypassword";

    Client client = ClientBuilder
            .newClient()
            .register(new Authenticator(user,password));

     String response = client
            .target("https://justanotherlink.com/jira/rest/api/2/issue/test")
            .request(MediaType.APPLICATION_JSON)
            .get(String.class);

    System.out.print(response);

}

它应该返回并打印出某种 json 格式的字符串,但它没有。它根本不打印任何内容。我试过了:

     Response response = client 
              ...
             .get(Response.class) 

打印出来了:

 InboundJaxrsResponse{context=ClientResponse{method=GET, uri=https://justanotherlink.com/jira/rest/api/2/issue/test, status=200, reason=200}}

关于状态/原因是 200(OK),我的请求通过了。知道为什么打印为 String 在这里不起作用吗? Postman 传递预期的 Json。

编辑: 它现在按预期工作。我唯一改变的是在打印之前将响应放入字符串变量中......我假设由于字符串的长度(大约 7000 个符号),Sysout 命令无法处理它或类似的东西

【问题讨论】:

    标签: java rest get client jira


    【解决方案1】:
    Response response = client 
                  ...
                 .get(Response.class) 
    

    是正确的。要检索内容,您需要

    String content = response.readEntity(String.class);
    System.out.print(content);
    

    【讨论】:

    • 感谢您的回答,但程序仍然以某种方式终止而不打印任何字符串。
    • 您是否添加了“System.out.print(content);” ?
    • 是的,我做到了 ^^ 但它似乎与我的第一个代码中的结果相同。这不是结果:o
    【解决方案2】:

    我发现有时(很少)它会打印出预期的结果。在大约 300 次尝试中只发生了 2 次。我不知道为什么,但即使我使用相同的代码,它有时也有效,有时无效。还要纠正自己:它不打印“无”它打印一堆空白。我假设它用空格替换了它应该打印的符号。仍然不知道为什么会发生这种情况......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-01
      • 2015-03-29
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 2016-03-16
      • 1970-01-01
      相关资源
      最近更新 更多