【问题标题】:How to consume REST in Java [duplicate]如何在 Java 中使用 REST [重复]
【发布时间】:2012-10-16 13:48:11
【问题描述】:

使用 Java 工具,

wscompile for RPC
wsimport for Document
etc..

我可以使用 WSDL 生成访问 SOAP Web 服务所需的存根和类。

但我不知道如何在 REST 中做同样的事情。 如何获取访问 REST Web 服务所需的 Java 类。 无论如何打服务的方法是什么?

谁能给我指路?

【问题讨论】:

标签: java web-services rest


【解决方案1】:

工作示例,试试这个:

package restclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetClientGet {
    public static void main(String[] args) {
        try {

            URL url = new URL("http://localhost:3002/RestWebserviceDemo/rest/json/product/dynamicData?size=5");//your url i.e fetch data from .
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP Error code : "
                        + conn.getResponseCode());
            }
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            BufferedReader br = new BufferedReader(in);
            String output;
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            conn.disconnect();

        } catch (Exception e) {
            System.out.println("Exception in NetClientGet:- " + e);
        }
    }
}

【讨论】:

  • @OwenIvory 你说的 apache 地狱是什么意思?
  • 我最初被告知使用 apache .jar 文件来完成一个简单的 Restful 查询。所以我下载了一些 .jar 文件,但它们是错误的 java 版本(不是我使用的那个)。然后我发现一些是正确的 java 版本,但它们与 apache 版本不匹配,因此这些类不包含我给出的示例所具有的对象。无论如何,这个例子是直接的 java.net.... 即只安装了 jdk。不用弄乱 apache 版本或获取 jar 文件或编译问题,只需 JDK 即可。
  • 嗨,如果我的方法是一个 Post 并且需要发送一个 Json 对象¿这可能在这个方法中吗?问候。
  • 我很困惑。哪种方法实际将请求发送到网络?是.openConnection()吗?如果是这样,您为什么要在之后设置请求方法和标头?原谅我,我还是个java初学者。
【解决方案2】:

正如其他人所说,您可以使用较低级别的 HTTP API 来执行此操作,或者您可以使用较高级别的 JAXRS API 将服务作为 JSON 来使用。例如:

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://host:8080/context/rest/method");
JsonArray response = target.request(MediaType.APPLICATION_JSON).get(JsonArray.class);

【讨论】:

  • 正如 Holly 所建议的,JAX RS 客户端 API(在 2.0 版中引入)比低级 URL + 手动解组更好地使用 REST API。我建议将数据作为正确映射的 Java bean 而不是“原始 json”。我之前写过的一个教程:vaadin.com/blog/-/blogs/…
  • 我可以用这个做一个 POST 请求吗?我如何设置请求的正文?
【解决方案3】:

只有两行代码。

import org.springframework.web.client.RestTemplate;

RestTemplate restTemplate = new RestTemplate();
YourBean obj = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", YourBean.class);

Ref. Spring.io consuming-rest

【讨论】:

  • 请留下 cmets 你为什么拒绝回答这个问题。
  • 你需要使用spring web,因为它使用的是RestTemplate
  • 我可以在 JEE 中使用 Spring REST 模板,还是有理由不这样做?
  • @powder366 可以添加需要的依赖并使用。
【解决方案4】:

下面的代码将有助于通过 Java 使用 rest api。 URL - 端点休息 如果您不需要任何身份验证,则不需要编写 authStringEnd 变量

该方法将在您的响应中返回一个 JsonObject

public JSONObject getAllTypes() throws JSONException, IOException {
        String url = "/api/atlas/types";
        String authString = name + ":" + password;
        String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
        javax.ws.rs.client.Client client = ClientBuilder.newClient();
        WebTarget webTarget = client.target(host + url);
        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON).header("Authorization", "Basic " + authStringEnc);

        Response response = invocationBuilder.get();
        String output = response.readEntity(String.class
        );

        System.out.println(response.toString());
        JSONObject obj = new JSONObject(output);

        return obj;
    }

【讨论】:

    【解决方案5】:

    只需使用正确的查询字符串或请求正文向所需的 URL 发出 http 请求。

    例如,您可以使用java.net.HttpURLConnection,然后通过connection.getInputStream() 消费,然后covnert 到您的对象。

    在春天有一个restTemplate 让一切变得更容易。

    【讨论】:

      【解决方案6】:

      如果您还需要转换作为对服务调用的响应的 xml 字符串,您需要的 x 对象可以按如下方式进行:

      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStreamReader;
      import java.io.StringReader;
      import java.net.HttpURLConnection;
      import java.net.MalformedURLException;
      import java.net.URL;
      import java.util.ArrayList;
      import java.util.List;
      
      import javax.xml.bind.JAXB;
      import javax.xml.bind.JAXBException;
      import javax.xml.parsers.DocumentBuilder;
      import javax.xml.parsers.DocumentBuilderFactory;
      import javax.xml.parsers.ParserConfigurationException;
      
      import org.w3c.dom.CharacterData;
      import org.w3c.dom.Document;
      import org.w3c.dom.Element;
      import org.w3c.dom.Node;
      import org.w3c.dom.NodeList;
      import org.xml.sax.InputSource;
      import org.xml.sax.SAXException;
      
      public class RestServiceClient {
      
      // http://localhost:8080/RESTfulExample/json/product/get
      public static void main(String[] args) throws ParserConfigurationException,
      SAXException {
      
      try {
      
      URL url = new URL(
          "http://localhost:8080/CustomerDB/webresources/co.com.mazf.ciudad");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/xml");
      
      if (conn.getResponseCode() != 200) {
      throw new RuntimeException("Failed : HTTP error code : "
          + conn.getResponseCode());
      }
      
      BufferedReader br = new BufferedReader(new InputStreamReader(
          (conn.getInputStream())));
      
      String output;
      
      Ciudades ciudades = new Ciudades();
      System.out.println("Output from Server .... \n");
      while ((output = br.readLine()) != null) {
      System.out.println("12132312");
      System.err.println(output);
      
      DocumentBuilder db = DocumentBuilderFactory.newInstance()
          .newDocumentBuilder();
      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(output));
      
      Document doc = db.parse(is);
      NodeList nodes = ((org.w3c.dom.Document) doc)
          .getElementsByTagName("ciudad");
      
      for (int i = 0; i < nodes.getLength(); i++) {
          Ciudad ciudad = new Ciudad();
          Element element = (Element) nodes.item(i);
      
          NodeList name = element.getElementsByTagName("idCiudad");
          Element element2 = (Element) name.item(0);
      
          ciudad.setIdCiudad(Integer
              .valueOf(getCharacterDataFromElement(element2)));
      
          NodeList title = element.getElementsByTagName("nomCiudad");
          element2 = (Element) title.item(0);
      
          ciudad.setNombre(getCharacterDataFromElement(element2));
      
          ciudades.getPartnerAccount().add(ciudad);
      }
      }
      
      for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
      System.out.println(ciudad1.getIdCiudad());
      System.out.println(ciudad1.getNombre());
      }
      
      conn.disconnect();
      
      } catch (MalformedURLException e) {
      e.printStackTrace();
      } catch (IOException e) {
      e.printStackTrace();
      }
      }
      
      public static String getCharacterDataFromElement(Element e) {
      Node child = e.getFirstChild();
      if (child instanceof CharacterData) {
      CharacterData cd = (CharacterData) child;
      return cd.getData();
      }
      return "";
      }
      }
      

      请注意,我在示例中预期的 xml 结构如下:

      <ciudad><idCiudad>1</idCiudad><nomCiudad>BOGOTA</nomCiudad></ciudad>
      

      【讨论】:

        【解决方案7】:

        看看Jersey。同样,REST 是关于数据的。还有教程here

        【讨论】:

        • 那是为了提供一个安静的服务
        • 并非如此,使用 Jersey,您不仅可以生成 RESTful Web 服务,还可以使用它们。
        【解决方案8】:

        JAX-RS 但您也可以使用标准 Java 附带的常规 DOM

        【讨论】:

          【解决方案9】:

          根据您的问题,不清楚您是否使用任何框架。对于 REST,您将获得 WADL 和 Apache CXF 最近添加了对 WADL 优先开发 REST 服务的支持。请通过http://cxf.apache.org/docs/index.html

          【讨论】:

          • 你的意思是我可以从 WADL 获取 Java 类吗?
          【解决方案10】:

          您可以使用 RestTemplate.class 在 Spring 中使用 Restful Web 服务。

          例子:

          public class Application {
          
              public static void main(String args[]) {
                  RestTemplate restTemplate = new RestTemplate();
                  ResponseEntity<String> call= restTemplate.getForEntity("http://localhost:8080/SpringExample/hello",String.class);
                  System.out.println(call.getBody())
              }
          
          }
          

          Reference

          【讨论】:

          • 您的 getForEntity 中缺少 String.class
          • 您没有向响应实体添加 be 类。 ResponseEntity call=restTemplate.getForEntity("localhost:8080/SpringExample/hello, String.class");它是一个字符串响应实体,您应该添加 bean 类 String.class 作为 .getForEntity 的第二个参数
          • 更新了代码
          • 我可以在 JEE 中使用 Spring REST 模板,还是有理由不这样做?
          • @powder366 是的,您可以在任何 java 项目中使用它,您只需添加项目的依赖项(spring-web)
          【解决方案11】:

          Apache Http Client API 非常常用于调用 HTTP Rest 服务。

          这是使用 HTTP GET 调用的示例之一。

          import java.io.IOException;
          import org.apache.http.HttpResponse;
          import org.apache.http.client.ClientProtocolException;
          import org.apache.http.client.HttpClient;
          import org.apache.http.client.methods.HttpGet;
          import org.apache.http.client.methods.HttpUriRequest;
          import org.apache.http.impl.client.HttpClientBuilder;
          
          public class CallHTTPGetService {
          
          public static void main(String[] args) throws ClientProtocolException, IOException {
          
          
              HttpClient client = HttpClientBuilder.create().build();
              HttpUriRequest httpUriRequest = new HttpGet("URL");
          
              HttpResponse response = client.execute(httpUriRequest);
              System.out.println(response);
          
          }
          }
          

          如果使用 Maven 项目,请使用以下 maven 依赖项。

          <dependency>
                  <groupId>org.apache.httpcomponents</groupId>
                  <artifactId>httpclient</artifactId>
                  <version>4.5.1</version>
              </dependency>
              <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
              <dependency>
                  <groupId>org.apache.httpcomponents</groupId>
                  <artifactId>httpmime</artifactId>
                  <version>4.5.1</version>
              </dependency>
          

          【讨论】:

            猜你喜欢
            • 2016-09-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-27
            • 1970-01-01
            • 2022-01-09
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多