私は始めます:私は何かひどく間違ったことをしています。そして、これが私が間違っていることです。
何かを検索するための REST リソースを作成しましたが、リクエスト パラメーターに JSON データが含まれていることを期待しています。
@GET
@Path("/device")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response searchContent(String searchJSONString) {
String message = new SearchServices().search(searchJSONString);
return getResponse(message); //Checks the message for any error and sends back the response.
}//end of searchContent()
私は書くべきではなかった:
@Consumes
これは GET リソースであり、何も消費しないためです。しかし、私の問題は、これ(GETリソース)のJavaコードでJSONデータを送信する方法です。このリソースにJSONデータを送信できるcurlコマンドを試しましたが、Javaコードは送信できませんでした。
次のcurlコマンドを試して、JSONデータを送信しました:
curl -X GET -H "Content-Type: application/json" -d '{"keyword":"hello"}' http://localhost:8080/search-test/rest/search
正常に動作し、適切な JSON 応答を返してくれます。
しかし、メソッド (デフォルトの http get である必要があります) を指定せずに curl コマンドを使用すると、Tomcat から 405 (メソッドが許可されていません) 応答が返されます。
curl -d '{"keyword":"hello"}' http://localhost:8080/search-test/rest/search
またはJavaコードを介して:
HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("GET"); //This is not working.
tomcat から同じ 405 (メソッドは許可されていません) 応答を取得します。
Java コードを使用して GET リクエストを送信している場合、POST メソッドのように JSON データを送信できず、name=value を使用せざるを得ないため、REST リソースを変更してそれを受け入れる必要があります。名前と値のペアとして。
次のような意味です。
http://localhost:8080/search-test/rest/search?param={"keyword":"permission"}
POSTで同様のことをしている場合:
@POST
@Path("/device")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response searchContent(String searchJSONString) {
String message = new SearchServices().search(searchJSONString);
return getResponse(message); //Checks the message for any error and sends back the response.
}//end of searchContent()
Java コードと curl コマンドの両方からも JSON データを送信できます。
curl -X POST -H "Content-Type: application/json" -d '{"keyword":"hello"}' http://localhost:8080/search-test/rest/search
またはJavaコードを介して:
HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
urlConnection.setRequestMethod("POST"); //Works fine.
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setDoOutput(true);
問題はどこだ?コードからではなくカールから送信できないのはなぜですか? name=value ペア以外に JSON データを GET リソースに送信する方法はありますか?