【问题标题】:how to call this url in java resful web service?如何在 java restful web 服务中调用这个 url?
【发布时间】:2016-05-24 10:09:55
【问题描述】:

谁能帮帮我?在这种情况下,如何在java restfull web service中调用这个服务url?http://jsonplaceholder.typicode.com/posts/1/comments

提前致谢。

【问题讨论】:

  • 我假设你想从这个 URL 获取数据,为了实现这个你可以使用 HttpClient 或者你可以简单地使用 URL Connection 从 URL 获取数据。

标签: java spring rest oop collections


【解决方案1】:

是否已经编写了 Java 客户端?如果没有,您可以使用 HttpClient 或 OkHttp 编写自己的代码(其他 HTTP 库可用)。

如果您从 Spring 容器内部调用(因为您使用 Spring 标签标记了这个问题),您可以使用 Spring RestTemplate。

【讨论】:

    【解决方案2】:

    试试下面的代码:-

    public static void main(String[] args) throws IOException {
    
        String theUrl = "http://jsonplaceholder.typicode.com/posts/1/comments";
         StringBuilder content = new StringBuilder();
        try
        {
          // create a url object
          URL url = new URL(theUrl);
    
          // create a urlconnection object
          URLConnection urlConnection = url.openConnection();
    
          // wrap the urlconnection in a bufferedreader
          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    
          String line;
    
          // read from the urlconnection via the bufferedreader
          while ((line = bufferedReader.readLine()) != null)
          {
            content.append(line + "\n");
          }
          bufferedReader.close();
        }
        catch(Exception e)
        {
          e.printStackTrace();
        }
        System.out.println(content);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-23
      • 2015-07-31
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 2018-01-01
      相关资源
      最近更新 更多