【问题标题】:POST in grails not workingPOST 在 grails 中不起作用
【发布时间】:2014-06-11 12:44:42
【问题描述】:

您好,我正在尝试在 grails 中进行 POST,我尝试了 2 种不同的方法。 我想复制这个 curl 命令:

 curl -F upload=@in.xml http://server.com/service.pl > out.xml

这个命令工作正常。 到目前为止我尝试过的如下:

  def actualInputFile = new File("/path/to/file/in.xml");


    def retval = [success: false, message: null];


        HttpClient postClient = new HttpClient();
        MultipartPostMethod postMethod = new MultipartPostMethod('http://server.com/service.pl');
        postClient.httpConnectionManager.getParams().setSoTimeout(300000);

        postMethod.addParameter("upload",actualInputFile);

        int status = postClient.executeMethod(postMethod);
        def data = postMethod.getResponseBodyAsString();
        postMethod.releaseConnection();
         def returnedFile = new File("/path/to/file/out.xml");
            returnedFile.write(data);

这会产生 500 错误

我也试过了:

  def actualInputFile = new File("/path/to/file/in.xml");

    def http = new HTTPBuilder( 'http://server.com/service.pl' )
    println "START POST"
    def postBody = [upload:actualInputFile] // will be url-encoded

    http.post( body: postBody,
            requestContentType: XML ) { resp ->

        println "POST Success: ${resp.statusLine}"
    }

这根本行不通。

获得 500 的第一个使用折旧方法。

有什么想法吗?

【问题讨论】:

    标签: rest grails post


    【解决方案1】:

    我假设您正在尝试从控制器运行此代码,如果是这样,我建议不要使用 commons-httpclient,因为它会引入许多依赖项,因为通常难以使​​用。与 Grails 一起使用的推荐客户端是 http://grails.org/plugin/rest-client-builder

    你的例子可以写成:

    def rest = new RestBuilder('http://server.com/service.pl' )
    def resp = rest.post(url) {
       upload = new File("/path/to/file/in.xml")
    }
    println resp.status
    

    尽管如此,如果您必须使用 commons-httpclient,如果您实际发布了您所看到的实际错误,这将有所帮助。只是说你得到 500 而不发布错误消息并没有太大帮助。

    【讨论】:

      【解决方案2】:

      这有点令人困惑。从 Perl 和 Curl 看来,您正试图将 XML 发布到 API。那是对的吗?

      如果是这样,您可以轻松地做到这一点,但您必须指定标头并构建您的 api 以接受 XML 并解释它。

      我可能会误解。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多