运行 来自 java 程序的 Advanced Rest Client 中的 URL

Running a URL in Advanced Rest Client from a java program

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

使用 Apache HttpClient 库 https://hc.apache.org/ 或一些其他第三方开源库来轻松编码。 如果您使用的是 apache httpClient 库,请 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);

如果对使用第三方 jar 有任何限制,您也可以直接使用 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();

  } 

简单地说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();
  }