私はUbuntuを使用しており、それにcURLをインストールしました。私のSpring RESTアプリケーションをcURLでテストしたいと思います。私はPOSTコードをJava側で書きました。しかし、私はそれをcURLでテストしたいのです。私は、JSONデータをポストしようとしています。データの例は次のようなものです。
{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}
私はこのコマンドを使用しています。
curl -i \
-H "Accept: application/json" \
-H "X-HTTP-Method-Override: PUT" \
-X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \
http://localhost:8080/xx/xxx/xxxx
このエラーが返されます。
HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT
エラーの説明はこうです。
リクエストエンティティが、リクエストされたリソースでサポートされていないフォーマットで、リクエストされたメソッド()でサポートされていないため、サーバーはこのリクエストを拒否しました。
Tomcatのログです。 "POST /ui/webapp/conf/clear HTTP/1.1" 415 1051
cURLコマンドの正しいフォーマットを教えてください。
これは、私のJava側のPUT
コードです(GETとDELETEをテストしましたが、動作しました)。
@RequestMapping(method = RequestMethod.PUT)
public Configuration updateConfiguration(HttpServletResponse response, @RequestBody Configuration configuration) { //consider @Valid tag
configuration.setName("PUT worked");
//todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
return configuration;
}
Content-Typeをapplication/jsonにする必要があります。しかし、-d
はContent-Type application/x-www-form-urlencoded
を送信しますが、これはSpring側では受け入れられません。
curl man page]1を見ると、-H
を使えばいいと思います。
-H "Content-Type: application/json"
完全な例です。
curl --header "Content-Type: application/json" \
--request POST \
--data '{"username":"xyz","password":"xyz"}' \
http://localhost:3000/api/login
(-H
は --header
の略、-d
は --data
の略)
dフラグは POST リクエストを意味するので、
-dを使用する場合、
-request POST` は オプション であることに注意してください。
Windowsでは、少し事情が異なります。コメントスレッドを参照してください。