将json发布到我的Web服务时,CURL无法正常工作

时间:2015-11-27 11:43:51

标签: json rest grails curl

我使用Grails 2.3.x创建了一个休息Web服务,如下所示:

import grails.rest.RestfulController
class CityController extends RestfulController{

static responseFormats = ['json', 'xml']
CityController() {
    super(City)
}
}

这是我的域类:

import groovy.transform.ToString
import groovy.transform.EqualsAndHashCode

/**
 * City
 * A domain class describes the data object and it's mapping to the database
 */

@ToString(includeNames = true, includeFields = true, excludes = 'dateCreated,lastUpdated,metaClass')
@EqualsAndHashCode
class City {

    /* Default (injected) attributes of GORM */
    Long    id
    Long    version

    /* Automatic timestamping of GORM */
    Date    dateCreated
    Date    lastUpdated

    String cityName
    String postalCode
    String countryCode // either iso2 or iso3



    static constraints = {
        postalCode blank:false, nullable:false
        cityName blank:false, nullable:false
        countryCode minSize:2, maxSize:3, blank:false, nullable:false, matches: "[A-Z]+"    
    }
}

这是urlMapping

class UrlMappings {

static mappings = {
    "/$controller/$action?/$id?(.$format)?"{
        constraints {
            // apply constraints here
        }
    }

    "/"(view:"/index")
    "500"(view:'/error')
    //
    // RESTService api
    "/api/city"(resources: 'city')
}
}

当我尝试使用curl获取数据时,我设法使用此行获取结果:

curl -X GET -H "Accept:application/json" http://localhost:8080/ComuneUtenti/city 

但是当我尝试将数据发布到我的WS时,我遇到了如下错误:

curl: (6) Could not resolve host: countryCode
curl: (6) Could not resolve host: postalCode
curl: (3) [globbing] unmatched close brace/bracket in column 6
{"errors":[{"object":"comuneutenti.City","field":"postalCode","rejected-value":null,"message":"property [postalCode] of class [class comuneutenti.City] cannot be null"},{"object":"comuneutenti.City","field":"cityName","rejected-value":null,"message":"property
[cityName] of class [class comuneutenti.City] cannot be null"},{"object":"comuneutenti.City","field":"countryCode","rejected-value":null,"message":"property[countryCode] of class [class comuneutenti.City] cannot be null"}]}

这是我的帖子:

curl -H "Content-Type:application/json" -X POST -d '{"cityName":"NewYork", "countryCode":"IT", "postalCode": "00166"}' http://localhost:8080/ComuneUtenti/api/city

我错过了什么?

我使用的是Grails 2.3.10 可以使用Postman调用相同的WS。

由于

2 个答案:

答案 0 :(得分:1)

您是否尝试过erichelgeson的建议?

正确的卷曲方法是

curl -H "Content-Type:application/json" -X POST -d '{"cityName":"NewYork", "countryCode":"IT", "postalCode": "00166"}' http://localhost:8080/ComuneUtenti/api/city

注意json有效负载周围的单引号。

要查看实际情况,可以使用echo命令。

$ echo {"hello":"world"}
{hello:world}

$ echo '{"hello":"world"}'
{"hello":"world"}

shell正在吃你田地周围的引号。

答案 1 :(得分:0)

您使用的是什么版本的grails 2.3? Grails 2.3.8有一个错误,你无法发布休息服务。

我相信这是在这里签到的。

https://github.com/grails/grails-core/commit/c050212fa0992f5b2d62c8e63795e4278fb2c3f4