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

时间:2011-11-01 16:59:00

标签: web-services spring httpclient resttemplate

在我的Spring Web应用程序中,我需要向非RESTful API发出HTTP请求,并将响应主体解析为String(它是单维CSV列表)。

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

Spring中是否有任何可以“开箱即用”的工作?

2 个答案:

答案 0 :(得分:3)

如果你看一下RestTemplate的来源,你会发现它在内部使用

java.net.URL

url.openConnection()

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

答案 1 :(得分:1)

我在内部使用带有Spring 4.3 Core的Spring Boot,并发现了一种非常简单的方法,可以使用OkHttpClient发出Http请求并读取响应。这是代码

public void sendSimpleSESMessage(){
    final String FROM = "test@sample.com";
    final String TO = "test@sample.com";
    final String SUBJECT = "Amazon SES test (AWS SDK for Java)";
    final String HTMLBODY = "<h1>Amazon SES test (AWS SDK for Java)</h1>"
            + "<p>This email was sent with <a href='https://aws.amazon.com/ses/'>"
            + "Amazon SES</a> using the <a href='https://aws.amazon.com/sdk-for-java/'>"
            + "AWS SDK for Java</a>";
    final String TEXTBODY = "This email was sent through Amazon SES "
            + "using the AWS SDK for Java.";
    try {
        AmazonSimpleEmailService client = awsClientService.getAmazonSESClient();
        log.info("Email Verification for " + FROM + " started");
        VerifyEmailIdentityResult verifyEmailIdentityResult = awsClientService.verifyEmailIdentity(client, FROM);
        log.info("Email verification for " + FROM + " completed");
        SendEmailRequest request = new SendEmailRequest()
                .withDestination(
                        new Destination().withToAddresses(TO))
                .withMessage(new com.amazonaws.services.simpleemail.model.Message()
                        .withBody(new Body()
                                .withHtml(new Content()
                                        .withCharset("UTF-8").withData(HTMLBODY))
                                .withText(new Content()
                                        .withCharset("UTF-8").withData(TEXTBODY)))
                        .withSubject(new Content()
                                .withCharset("UTF-8").withData(SUBJECT)))
                .withSource(FROM);
        client.sendEmail(request);
        log.info("Email was sent from "+FROM+" to "+TO);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}