![](/img/trans.png)
[英]Why am I getting a 500 response for my POST on my Jersey REST API?
[英]Why am I getting response status of 204 No content in my REST server?
我是REST API的新手,並且通常與服務器一起使用,我正在嘗試制作一個簡單的客戶端-服務器應用程序。 我正在使用澤西島。
客戶端向服務器發送一些數據,服務器接收數據並將其顯示在所需的uri上,反之亦然。
反之亦然,接收服務器上托管的數據可以正常工作,但是我無法將數據發送到服務器。
我試過像這樣的POST:
@POST
@Path("/something")
@Consumes("application/x-www-form-urlencoded")
public void getSomething(){
}
我的客戶端代碼如下所示:
Client client = Client.create();
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
WebResource resource = client.resource("http://localhost:8080/artifact/rest/something");
ClientResponse response = resource.type("application/x-www-form-urlencoded").post(ClientResponse.class, formData);
System.out.println(response);
我正在嘗試將字符串或json類型的對象發送到服務器,並且應該在該url上顯示它。 但是我不能這樣做。
如果有人可以幫助我,我將不勝感激。
編輯我也很感激,如果有人能告訴我如何使用這樣的代碼將數據發送到服務器。
嘗試將這種格式用於jersey服務器端,盡管所使用的相同:
@POST
@Path("your path")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
對於客戶端,請嘗試使用此功能。
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url + "/rest/something");
post.addHeader("Accept" , "application/json");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name1", "val1"));
params.add(new BasicNameValuePair("name2", "val2"));
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpClient.execute(post);
String out = EntityUtils.toString(response.getEntity());
你的getSomething
沒有返回任何東西。 轉換為204 No Content
響應:操作成功(代碼2xx
指示此操作),但是沒有任何返回值。
如果要返回某些內容,請將返回類型從void
更改為Response
。
@POST
@Path("/something")
@Consumes("application/x-www-form-urlencoded")
@Produces("text/plain")
public Response getSomething() {
return Response.ok("Success!").build();
}
這將返回HTTP狀態代碼200 OK
, Success!
作為回應機構的內容。
但您可能希望以某種方式使用請求的內容。 查看jax-rs檢索表單參數以了解如何執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.