RESTEasy クライアント フレームワークを使用して RESTful Web サービスを呼び出しています。呼び出しは POST 経由で行われ、XML データがサーバーに送信されます。どうすればこれを達成できますか?
これを実現するために使用する注釈の魔法の呪文は何ですか?
David は RESTeasy の「クライアント フレームワーク」について言及していると思います。したがって、あなたの答え (Riduidel) は、特に彼が探しているものではありません。ソリューションは、http クライアントとして HttpUrlConnection を使用します。resteasy クライアントは JAX-RS に対応しているため、HttpUrlConnection または DefaultHttpClient の代わりに resteasy クライアントを使用すると有益です。RESTeasy クライアントを使用するには、org.jboss.resteasy.client.ClientRequest オブジェクトを構築し、そのコンストラクターとメソッドを使用してリクエストを構築します。以下は、RESTeasy のクライアント フレームワークを使用して David の質問を実装する方法です。
ClientRequest request = new ClientRequest("http://url/resource/{id}");
StringBuilder sb = new StringBuilder();
sb.append("<user id=\"0\">");
sb.append(" <username>Test User</username>");
sb.append(" <email>test.user@test.com</email>");
sb.append("</user>");
String xmltext = sb.toString();
request.accept("application/xml").pathParameter("id", 1).body( MediaType.APPLICATION_XML, xmltext);
String response = request.postTarget( String.class); //get response and automatically unmarshall to a string.
//or
ClientResponse<String> response = request.post();
これが役に立てば幸いです、チャーリー
次のように簡単です
@Test
public void testPost() throws Exception {
final ClientRequest clientCreateRequest = new ClientRequest("http://localhost:9090/variables");
final MultivaluedMap<String, String> formParameters = clientCreateRequest.getFormParameters();
final String name = "postVariable";
formParameters.putSingle("name", name);
formParameters.putSingle("type", "String");
formParameters.putSingle("units", "units");
formParameters.putSingle("description", "description");
formParameters.putSingle("core", "true");
final ClientResponse<String> clientCreateResponse = clientCreateRequest.post(String.class);
assertEquals(201, clientCreateResponse.getStatus());
}
この例から借りました: RESTEasy で安らかなサービスを構築するには、次のコード フラグメントを使用します。
URL url = new URL("http://localhost:8081/user");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
StringBuffer sbuffer = new StringBuffer();
sbuffer.append("<user id=\"0\">");
sbuffer.append(" <username>Test User</username>");
sbuffer.append(" <email>test.user@test.com</email>");
sbuffer.append("</user>");
OutputStream os = connection.getOutputStream();
os.write(sbuffer.toString().getBytes());
os.flush();
assertEquals(HttpURLConnection.HTTP_CREATED, connection.getResponseCode());
connection.disconnect();