繁体   English   中英

如何使用http POST JAX-RS将对象从AngularJS服务传递给Java

[英]How can I pass an Object from an AngularJS Service to Java using http POST JAX-RS

因此,我正在构建一个电子邮件客户端,该客户端对Google API进行授权的RESTful调用(OAuth 2和JAX-RS)。

我已经成功导入了电子邮件和联系人。 我现在想发送一封电子邮件。

我有一个成功调用服务的控制器

app.controller('ComposeController', function($scope, $cookies, ComposeService) {

    //Some test data
    var email = $cookies.email;
    $scope.to = "********@yahoo.com";
    $scope.subject = "test";
    $scope.body = "test";

    $scope.compose = function() {

        //Create an email object
        $scope.newEmail = {
                'to' : $scope.to,
                'from' : email,
                'subject' : $scope.subject,
                'body' : $scope.body
        };

        //Parse to JSON
        var emailJSON = angular.toJson($scope.newEmail);

        //Make call to ComposeService
        var response = ComposeService.compose(emailJSON).success(function(jsonData) {

            response = jsonData;
            alert(response);
        });
    }
});

然后,服务调用Java类

app.factory('ComposeService', function($http) {

    var response = {};

    response.compose = function(newEmail) {

        return $http({

            method: 'POST',
            url: 'resources/composeMail/send',
            data: {
                newEmail : newEmail
            },
            headers: {'Content-Type':'application/json'}
        });
    }

    return response;
});

这是被称为类

@Path("/composeMail")
public class Compose {

    @POST
    @Path("/send")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String sendMessage(NewEmail newEmail) throws MessagingException,
            IOException {

        System.out.println("I am here");
    .....

这是NewEmail对象

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class NewEmail {

    private String to;
    private String from;
    private String subject;
    private String body; 

    public NewEmail(String to, String from, String subject, String body) {
        this.to = to;
        this.from = from;
        this.subject = subject;
        this.body = body;
    }
......

Java类不会被调用。 我收到400响应(错误的请求)。 如果我从构造函数中删除“ NewEmail newEmail”,则确实会调用该类,并且会看到预期的输出。

谢谢。

乍一看,JS代码看起来还可以。 但是,您需要在JAX-RS方面进行一些工作。 这是因为JAX-RS不知道如何在请求中的JSON与NewEmail类之间进行转换。

您有2个选项:

  1. 为您的NewEmail类编写一个自定义Provider 例如参见此链接
  2. 更改method参数以接受JSON并将其转换为方法。 从长远来看,这可能不太理想。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM