Web services 在Spring中发出HTTP请求的最简单方法

Web services 在Spring中发出HTTP请求的最简单方法,web-services,spring,httpclient,resttemplate,Web Services,Spring,Httpclient,Resttemplate,在SpringWeb应用程序中,我需要向非RESTful API发出HTTP请求,并将响应体解析为字符串(它是一个一维CSV列表) 我以前使用过restemplate,但这不是RESTful,也不能很好地映射到类。每当我“手工”实现类似的东西时(例如使用HttpClient),我总是在后来发现Spring有一个实用程序类,使事情变得更简单 Spring中有什么东西可以“开箱即用”完成这项工作吗?如果您查看RestTemplate的源代码,您会发现它在内部使用 java.net.URL 及 这是

在SpringWeb应用程序中,我需要向非RESTful API发出HTTP请求,并将响应体解析为字符串(它是一个一维CSV列表)

我以前使用过
restemplate
,但这不是RESTful,也不能很好地映射到类。每当我“手工”实现类似的东西时(例如使用
HttpClient
),我总是在后来发现Spring有一个实用程序类,使事情变得更简单


Spring中有什么东西可以“开箱即用”完成这项工作吗?

如果您查看RestTemplate的源代码,您会发现它在内部使用

java.net.URL


这是Java中进行HTTP调用的标准方法,因此您可以安全地使用它。如果spring中有一个“HTTP客户机”实用程序,那么RestTemplate也会使用它。

我使用spring引导,内置spring 4.3内核,并找到了一种使用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
        }

进口在这里会很有帮助。
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
        }