2011-01-25 22 views
1

來自netbeans,我使用內置的嚮導創建了一個新的REST webservice(使用球衣)。在容器資源類中,它創建了一個存根,運動衫(JSR-311),如何在容器模式下實現@POST

@POST 
@Consumes("application/json") 
@Produces("application/json") 
public Response postJson(Identity identity) { 
    identities.addIdentity(identity); 
    return Response.status(Status.OK).entity(identity).build(); 
} 

如何POST到此?我的理解是需要發佈name = val對。球衣在這裏期待什麼?我將如何使用curl發佈json到這個?這是我試過的,

#!/bin/bash 

DATA="{ \"id\": \"$1\", \"vcard\": \"$2\", \"location\": { \"latitude\": \"$3\", \"longitude\": \"$4\" } }" 
echo "posting: $DATA" 
HEADER='Content-Type:application/json' 
URL='http://localhost:8080/contacthi-proximity-service/resources/is' 
curl --data-binary "${DATA}" -H "${HEADER}" "${URL}" 

當我發佈這個,看看身份對象進來,所有的字段都是空的?我懷疑我的JSON不正確。當我手動對象添加到我的容器,然後形成一個東西,我看到這樣的結果,

{"identities":{"id":"Foo Bar","vcard":"VCARD123","location":{"latitude":"-1.0","longitude":"-1.0"}}} 

當我嘗試後同樣的事情,所有字段都爲空。我也試過,

{"id":"Foo Bar","vcard":"VCARD123","location":{"latitude":"-1.0","longitude":"-1.0"}} 

同樣的結果。 ?謝謝。

謝謝。

回答

1

將請求發送到使用curl這個方法,你將不得不使用這樣的:

HEADER='--header Content-Type:application/json' 
URL='http://localhost:<port>/methodName' 
curl --data-binary request.json ${HEADER} ${URL} -D response.txt 

您可以將字符串傳遞給方法。上面的代碼會從提到的文件中選擇json字符串。樣品JSON可能是:

{"userName":"test","timestamp":"2010-08-05T11:35:32.982-0800","userId":"0982"} 

爲了創建響應,你可以使用這樣的:使用

return Response.status(Status.OK).entity(responseString).build(); 

類是:

import javax.ws.rs.core.Response; 
import javax.ws.rs.core.Response.Status; 
+0

我想這一點,並據此編輯的問題。服務器似乎不喜歡那個請求。它從來沒有得到我的代碼。 – 2011-01-25 18:14:02