【问题标题】:Running a URL in Advanced Rest Client from a java program从 Java 程序在 Advanced Rest Client 中运行 URL
【发布时间】:2015-05-14 05:18:29
【问题描述】:

我有一个 API 的 URL,如果直接在 chrome 的高级 rest 客户端中运行,它可以正常工作。我希望这个 URL 从我自己的 REST API 代码中触发,该代码应该在高级休息客户端中运行它并将结果存储在变量中。 我该怎么做?

【问题讨论】:

  • 为什么需要它在高级REST客户端中运行?

标签: java rest google-chrome rest-client


【解决方案1】:

使用 Apache HttpClient 库 https://hc.apache.org/ 或其他一些第三方开源库来轻松编码。 如果您使用的是 apache httpClient lib,请 google 获取示例代码。小例子就在这里。

  HttpClient client = new DefaultHttpClient();
  HttpGet request = new HttpGet('http://site/MyrestUrl');
  HttpResponse response = client.execute(request);
  BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
  String line = '';
  while ((line = rd.readLine()) != null) {
    System.out.println(line);
  }
  return (rd);

如果使用第三方 jars 有任何限制,你也可以使用普通 java。

  HttpURLConnection conn = null;
   try {

    URL url = new URL("http://site/MyRestURL");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", ""); // add your content mime type

    if (conn.getResponseCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(
        (conn.getInputStream())));

    String output;
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    conn.disconnect();

  } catch (Exception e) {

    e.printStackTrace();

  } 

【讨论】:

  • 感谢您的回答。它帮助我处理带有 http 的 url。但它不适用于https。我试图为 https 寻找类似的结构,但找不到任何结构。你能帮我一些链接或这样的结构,它采用 https url。谢谢。
  • 请查看问题和答案。如果您想要证书解决方案,它可以帮助您。 stackoverflow.com/questions/1757295/…
  • 这是一个很好解释的博客。 javaskeleton.blogspot.de/2010/07/…
【解决方案2】:

在普通的java中,试试这样。我的建议请尝试使用好的开源 rest/http 客户端。网上有很多例子。

  String httpsUrl = "https://www.google.com/";
  URL url;
  try {
     url = new URL(httpsUrl);
     HttpsURLConnection con = HttpsURLConnection)url.openConnection();
    } catch (MalformedURLException e) {
     e.printStackTrace();
  } catch (IOException e) {
     e.printStackTrace();
  }

【讨论】:

    猜你喜欢
    • 2020-01-23
    • 2016-03-01
    • 2017-02-01
    • 2016-11-15
    • 2021-02-06
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多