在Spring中最简单的发起HTTP请求的方法

5
在我的Spring Web应用程序中,我需要向非RESTful API发出HTTP请求,并将响应正文解析为字符串(它是一个单维CSV列表)。
我之前使用过RestTemplate,但这不是RESTful,也无法很好地映射到类上。每当我手动实现这样的东西时(例如使用HttpClient),我总是后来发现Spring有一个实用程序类可以使事情变得简单。
在Spring中是否有任何“开箱即用”的东西可以完成此工作?
2个回答

5
如果你查看RestTemplate源代码,你会发现它在内部使用了。
java.net.URL

并且
url.openConnection()

这是在Java中进行HTTP调用的标准方式,因此您可以放心使用。如果Spring中有一个“HTTP客户端”实用程序,则RestTemplate也会使用它。


3

我使用了Spring Boot和Spring 4.3 Core,发现使用OkHttpClient可以非常简单地进行Http请求并读取响应。以下是代码:

Request request = new Request.Builder().method("PUT", "some your request body")
            .url(YOUR_URL)
            .build();
        OkHttpClient httpClient = new OkHttpClient();
        try
        {
            Response response = httpClient.newBuilder()
            .readTimeout(1, TimeUnit.SECONDS)
            .build()
            .newCall(request)
            .execute();
            if(response.isSuccessful())
            {
                // notification about succesful request
            }
            else
            {
                // notification about failure request
            }
        }
        catch (IOException e1)
        {
            // notification about other problems
        }

10
进口货物在这里会非常有帮助。 - greymatter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接