Java 中的 RESTful 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3913502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:46:49  来源:igfitidea点击:

RESTful call in Java

javarest

提问by Questions

I am going to make a RESTful call in Java. However, I don't know how to make the call. Do I need to use the URLConnection or others? Can anyone help me. thank you.

我将在 Java 中进行 RESTful 调用。但是,我不知道如何拨打电话。我是否需要使用 URLConnection 或其他?谁能帮我。谢谢你。

采纳答案by Buhake Sindi

If you are calling a RESTful service from a Service Provider (e.g Facebook, Twitter), you can do it with any flavourof your choice:

如果您从服务提供商(例如 Facebook、Twitter)调用 RESTful 服务,您可以使用您选择的任何风格

If you don't want to use external libraries, you can use java.net.HttpURLConnectionor javax.net.ssl.HttpsURLConnection(for SSL), but that is call encapsulated in a Factory type pattern in java.net.URLConnection. To receive the result, you will have to connection.getInputStream()which returns you an InputStream. You will then have to convert your input stream to string and parse the string into it's representative object (e.g. XML, JSON, etc).

如果您不想使用外部库,您可以使用java.net.HttpURLConnectionor javax.net.ssl.HttpsURLConnection(对于 SSL),但这是封装在java.net.URLConnection. 要接收结果,您必须向connection.getInputStream()which 返回一个InputStream. 然后,您必须将输入流转换为字符串并将字符串解析为它的代表对象(例如 XML、JSON 等)。

Alternatively, Apache HttpClient(version 4 is the latest). It's more stable and robust than java's default URLConnectionand it supports most (if not all) HTTP protocol (as well as it can be set to Strict mode). Your response will still be in InputStreamand you can use it as mentioned above.

或者,Apache HttpClient(版本 4 是最新的)。它比 java 的默认值更稳定和健壮URLConnection,并且支持大多数(如果不是全部)HTTP 协议(​​以及它可以设置为严格模式)。您的回复仍然存在InputStream,您可以按照上面提到的方式使用它。



Documentation on HttpClient: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

HttpClient 上的文档:http: //hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

回答by Qwerky

There are several RESTful APIs around. I would recommend Jersey;

周围有几个 RESTful API。我会推荐泽西岛;

https://jersey.java.net/

https://jersey.java.net/

Client API documentation is here;

客户端 API 文档在这里;

https://jersey.java.net/documentation/latest/index.html

https://jersey.java.net/documentation/latest/index.html

Update
Location for the OAuth docs in the comment below is a dead link and has moved to https://jersey.java.net/nonav/documentation/latest/security.html#d0e12334


下面评论中 OAuth 文档的更新位置是一个死链接,并已移至 https://jersey.java.net/nonav/documentation/latest/security.html#d0e12334

回答by Sean Patrick Floyd

This is very complicated in java, which is why I would suggest using Spring's RestTemplateabstraction:

这在 java 中非常复杂,这就是为什么我建议使用 Spring 的RestTemplate抽象:

String result = 
restTemplate.getForObject(
    "http://example.com/hotels/{hotel}/bookings/{booking}",
    String.class,"42", "21"
);

Reference:

参考:

回答by jitter

If you just need to make a simple call to a REST service from java you use something along these line

如果您只需要从 Java 对 REST 服务进行简单调用,您可以使用这些方法

/*
 * Stolen from http://xml.nig.ac.jp/tutorial/rest/index.html
 * and http://www.dr-chuck.com/csev-blog/2007/09/calling-rest-web-services-from-java/
*/
import java.io.*;
import java.net.*;

public class Rest {

    public static void main(String[] args) throws IOException {
        URL url = new URL(INSERT_HERE_YOUR_URL);
        String query = INSERT_HERE_YOUR_URL_PARAMETERS;

        //make connection
        URLConnection urlc = url.openConnection();

        //use post mode
        urlc.setDoOutput(true);
        urlc.setAllowUserInteraction(false);

        //send query
        PrintStream ps = new PrintStream(urlc.getOutputStream());
        ps.print(query);
        ps.close();

        //get result
        BufferedReader br = new BufferedReader(new InputStreamReader(urlc
            .getInputStream()));
        String l = null;
        while ((l=br.readLine())!=null) {
            System.out.println(l);
        }
        br.close();
    }
}

回答by Joopiter

You can check out the CXF. You can visit the JAX-RS Article here

您可以查看CXF。您可以在此处访问 JAX-RS 文章

Calling is as simple as this (quote):

调用就这么简单(引用):

BookStore store = JAXRSClientFactory.create("http://bookstore.com", BookStore.class);
// (1) remote GET call to http://bookstore.com/bookstore
Books books = store.getAllBooks();
// (2) no remote call
BookResource subresource = store.getBookSubresource(1);
// {3} remote GET call to http://bookstore.com/bookstore/1
Book b = subresource.getDescription();

回答by Avi Flax

Update:It's been almost 5 years since I wrote the answer below; today I have a different perspective.

更新:我写下面的答案已经快 5 年了;今天我有不同的看法。

99% of the time when people use the term REST, they really mean HTTP; they could care less about “resources”, “representations”, “state transfers”, “uniform interfaces”, “hypermedia”, or any other constraints or aspects of the REST architecture style identified by Fielding. The abstractions provided by various REST frameworks are therefore confusing and unhelpful.

当人们使用术语 REST 时,99% 的情况下他们真正指的是 HTTP;他们可能不太关心“资源”、“表示”、“状态传输”、“统一接口”、“超媒体”或Fielding 确定的 REST 架构风格的任何其他约束或方面。因此,各种 REST 框架提供的抽象令人困惑且无益。

So: you want to send HTTP requests using Java in 2015. You want an API that is clear, expressive, intuitive, idiomatic, simple. What to use? I no longer use Java, but for the past few years the Java HTTP client library that has seemed the most promising and interesting is OkHttp. Check it out.

所以:你想在 2015 年使用 Java 发送 HTTP 请求。你想要一个清晰、富有表现力、直观、惯用、简单的 API。用什么?我不再使用 Java,但在过去几年中,似乎最有前途和最有趣的 Java HTTP 客户端库是OkHttp。一探究竟。



You can definitely interact with RESTful web services by using URLConnectionor HTTPClientto code HTTP requests.

您绝对可以通过使用URLConnectionHTTPClient对 HTTP 请求进行编码来与 RESTful Web 服务进行交互。

However, it's generally more desirable to use a library or framework which provides a simpler and more semantic API specifically designed for this purpose. This makes the code easier to write, read, and debug, and reduces duplication of effort. These frameworks generally implement some great features which aren't necessarily present or easy to use in lower-level libraries, such as content negotiation, caching, and authentication.

但是,通常更希望使用一个库或框架来提供专门为此目的而设计的更简单、更具语义的 API。这使代码更易于编写、阅读和调试,并减少重复工作。这些框架通常实现了一些在低级库中不一定存在或易于使用的强大功能,例如内容协商、缓存和身份验证。

Some of the most mature options are Jersey, RESTEasy, and Restlet.

一些最成熟的选项是JerseyRESTEasyRestlet

I'm most familiar with Restlet, and Jersey, let's look at how we'd make a POSTrequest with both APIs.

我最熟悉 Restlet 和 Jersey,让我们看看我们如何POST使用这两个 API 发出请求。

Jersey Example

泽西岛示例

Form form = new Form();
form.add("x", "foo");
form.add("y", "bar");

Client client = ClientBuilder.newClient();

WebTarget resource = client.target("http://localhost:8080/someresource");

Builder request = resource.request();
request.accept(MediaType.APPLICATION_JSON);

Response response = request.get();

if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
    System.out.println("Success! " + response.getStatus());
    System.out.println(response.getEntity());
} else {
    System.out.println("ERROR! " + response.getStatus());    
    System.out.println(response.getEntity());
}

Restlet Example

Restlet示例

Form form = new Form();
form.add("x", "foo");
form.add("y", "bar");

ClientResource resource = new ClientResource("http://localhost:8080/someresource");

Response response = resource.post(form.getWebRepresentation());

if (response.getStatus().isSuccess()) {
    System.out.println("Success! " + response.getStatus());
    System.out.println(response.getEntity().getText());
} else {
    System.out.println("ERROR! " + response.getStatus());
    System.out.println(response.getEntity().getText());
}

Of course, GET requests are even simpler, and you can also specify things like entity tags and Acceptheaders, but hopefully these examples are usefully non-trivial but not too complex.

当然,GET 请求更简单,您还可以指定诸如实体标签和Accept标头之类的内容,但希望这些示例非常有用,但不会太复杂。

As you can see, Restlet and Jersey have similar client APIs. I believe they were developed around the same time, and therefore influenced each other.

如您所见,Restlet 和 Jersey 具有类似的客户端 API。我相信它们是在同一时间开发的,因此相互影响。

I find the Restlet API to be a little more semantic, and therefore a little clearer, but YMMV.

我发现 Restlet API 更语义化,因此更清晰一点,但 YMMV。

As I said, I'm most familiar with Restlet, I've used it in many apps for years, and I'm very happy with it. It's a very mature, robust, simple, effective, active, and well-supported framework. I can't speak to Jersey or RESTEasy, but my impression is that they're both also solid choices.

正如我所说,我最熟悉Restlet,多年来我已经在许多应用程序中使用它,我对它非常满意。它是一个非常成熟、健壮、简单、有效、活跃且支持良好的框架。我无法与 Jersey 或 RESTEasy 交谈,但我的印象是它们也是可靠的选择。

回答by Lisandro

I want to share my personal experience, calling a REST WS with Post JSON call:

我想分享我的个人经验,使用 Post JSON 调用调用 REST WS:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;

public class HWS {

    public static void main(String[] args) throws IOException {
        URL url = new URL("INSERT YOUR SERVER REQUEST");
        //Insert your JSON query request
        String query = "{'PARAM1': 'VALUE','PARAM2': 'VALUE','PARAM3': 'VALUE','PARAM4': 'VALUE'}";
        //It change the apostrophe char to double colon char, to form a correct JSON string
        query=query.replace("'", "\"");

        try{
            //make connection
            URLConnection urlc = url.openConnection();
            //It Content Type is so importan to support JSON call
            urlc.setRequestProperty("Content-Type", "application/xml");
            Msj("Conectando: " + url.toString());
            //use post mode
            urlc.setDoOutput(true);
            urlc.setAllowUserInteraction(false);

            //send query
            PrintStream ps = new PrintStream(urlc.getOutputStream());
            ps.print(query);
            Msj("Consulta: " + query);
            ps.close();

            //get result
            BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
            String l = null;
            while ((l=br.readLine())!=null) {
                Msj(l);
            }
            br.close();
        } catch (Exception e){
            Msj("Error ocurrido");
            Msj(e.toString());
        }
    }

    private static void Msj(String texto){
        System.out.println(texto);
    }
}

回答by JRun

Indeed, this is "very complicated in Java":

事实上,这“在 Java 中非常复杂”:

From: https://jersey.java.net/documentation/latest/client.html

来自:https: //jersey.java.net/documentation/latest/client.html

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://foo").path("bar");
Invocation.Builder invocationBuilder = target.request(MediaType.TEXT_PLAIN_TYPE);
Response response = invocationBuilder.get();

回答by kayz1

You can use Async Http Client(The library also supports the WebSocketProtocol) like that:

您可以像这样使用异步 Http 客户端(该库还支持WebSocket协议):

    String clientChannel = UriBuilder.fromPath("http://localhost:8080/api/{id}").build(id).toString();

    try (AsyncHttpClient asyncHttpClient = new AsyncHttpClient())
    {
        BoundRequestBuilder postRequest = asyncHttpClient.preparePost(clientChannel);
        postRequest.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        postRequest.setBody(message.toString()); // returns JSON
        postRequest.execute().get();
    }

回答by Hemin

Most Easy Solution will be using Apache http client library. refer following sample code.. this code uses basic security for authenticating.

最简单的解决方案将使用 Apache http 客户端库。请参阅以下示例代码。此代码使用基本安全性进行身份验证。

Add following Dependency.

添加以下依赖项。

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
Credentials credentials = new UsernamePasswordCredentials("username", "password");
credentialsProvider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
HttpPost request = new HttpPost("https://api.plivo.com/v1/Account/MAYNJ3OT/Message/");HttpResponse response = client.execute(request);
    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {    
    textView = textView + line;
    }
    System.out.println(textView);