我刚开始在REST工作。以下是我的完整源代码。我尝试过JSON类型,甚至是纯文本(TEXT / PLAIN)类型。还在
不允许使用HTTP 405方法。
JerseyClient:
package com.post;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientPost {
public static void main(String[] args) {
try{
// TODO Auto-generated method stub
Client client = Client.create();
WebResource r = client.resource("http://localhost:8080/PostExample/rest/priya/metallica/post");
String input = "{\"singer\":\"Metallica\",\"title\":\"Fade To Black\"}";
ClientResponse resp = r.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, input);
if (resp.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ resp.getStatus());
}
System.out.println("Output from Server .... \n");
String output = resp.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
资源:
package com.post;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/priya/metallica")
public class JSONService {
@POST
@Path("/post")
@Consumes(MediaType.TEXT_PLAIN)
public Response createTrackInJSON(Track track) {
String result = "Track saved : " + track;
return Response.status(201).entity(result).build();
}
}
POJO课程:
package com.post;
public class Track {
private String singer;
private String title;
public String getSinger(){
return singer;
}
public void setSinger(String singer){
this.singer=singer;
}
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title =title;
}
}
的web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>PostExample</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.post</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
我也尝试使用XMl格式,在pojo / resource / client中使用相应的注释,但发生了相同的HTTP 405错误。
答案 0 :(得分:0)
据我所知,传递对象时应使用application/json
媒体类型。所以,我会在代码中使用它,并在client.produce
中使用它。
答案 1 :(得分:0)
尝试以下步骤来解决上述问题。