java 在 RESTEasy 中使用 POST 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33991559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Consuming POST Request in RESTEasy
提问by Coding Bad
Earlier, I used POSTMAN tool to submit GET/PUT/POST/DELETE but right now I am trying to implement a POST operation without using any REST API client. For this purpose I referred to this website. I created a Maven project and these are my sample codes:
早些时候,我使用 POSTMAN 工具提交 GET/PUT/POST/DELETE 但现在我正在尝试在不使用任何 REST API 客户端的情况下实现 POST 操作。为此,我参考了 这个网站。我创建了一个 Maven 项目,这些是我的示例代码:
web.xml
网页.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>RESTEasyJSONExample</display-name>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<!-- Auto scan REST service -->
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
<!-- this should be the same URL pattern as the servlet-mapping property -->
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
</servlet>
pom.xml
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.java.resteasy</groupId>
<artifactId>RESTEasyJSONExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<repositories>
<repository>
<id>JBoss repository</id>
<url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>3.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-Hymanson-provider</artifactId>
<version>3.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.4.Final</version>
</dependency>
</dependencies>
Java Class to be represented to JSON
要表示为 JSON 的 Java 类
(Student.java)
(学生.java)
package org.jboss.resteasy;
public class Student {
private int id;
private String firstName;
private String lastName;
private int age;
// No-argument constructor
public Student() {
}
public Student(String fname, String lname, int age, int id) {
this.firstName = fname;
this.lastName = lname;
this.age = age;
this.id = id;
}
//getters and settters
@Override
public String toString() {
return new StringBuffer(" First Name : ").append(this.firstName)
.append(" Last Name : ").append(this.lastName)
.append(" Age : ").append(this.age).append(" ID : ")
.append(this.id).toString();
}
}
REST Service to produce and consume JSON output
用于生成和使用 JSON 输出的 REST 服务
RESTEasyJSONServices.java
RESTEasyJSONServices.java
package org.jboss.resteasy;
//import everything here
@Path("/jsonresponse")
public class RestEasyJSONServices {
@GET
@Path("/print/{name}")
@Produces("application/json")
public Student produceJSON( @PathParam("name") String name ) {
Student st = new Student(name, "Marco",19,12);
return st;
}
@POST
@Path("/send")
@Consumes("application/json")
public Response consumeJSON(Student student) {
String output = student.toString();
return Response.status(200).entity(output).build();
}
}
RESTEasyClient.java
RESTEasyClient.java
package org.jboss.resteasy.restclient;
//import everything here
public class RESTEasyClient {
public static void main(String[] args) {
Student st = new Student("Catain", "Hook", 10, 12);
try {
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://localhost:8080/RESTEasyJSONExample/rest/jsonresponse/send");
Response response = target.request().post(Entity.entity(st, "application/json"));
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Server response : \n");
System.out.println(response.readEntity(String.class));
response.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now I am getting the output whenever I use the GET url:
现在,每当我使用 GET url 时,我都会得到输出:
http://localhost:8080/RESTEasyJSONExample/rest/jsonresponse/print/James
which is basically used to produce the JSON but when I use the POST url which is http://localhost:8080/RESTEasyJSONExample/rest/jsonresponse/send
I do not get any response. Am I using the correct URL? Where am I doing wrong? My overall purpose is to implement POST method using JSON or XML without using any REST Client tool like POSTMAN.
这基本上用于生成 JSON,但是当我使用 POST url 时,http://localhost:8080/RESTEasyJSONExample/rest/jsonresponse/send
我没有得到任何响应。我是否使用了正确的 URL?我哪里做错了?我的总体目的是使用 JSON 或 XML 实现 POST 方法,而不使用任何像 POSTMAN 这样的 REST 客户端工具。
回答by Rahul Sharma
HI i have Used Jersey Client to post the request. i am able to post XML data. that should work for Json also. Please refer how to build REST Client: http://entityclass.in/rest/jerseyClientGetXml.htm
嗨,我已使用 Jersey 客户端发布请求。我能够发布 XML 数据。这也适用于 Json。请参考如何构建 REST Client:http: //entityclass.in/rest/jerseyClientGetXml.htm
REST Service
休息服务
@Path("/StudentService")
public class StudentService {
@POST
@Path("/update")
@Consumes(MediaType.APPLICATION_XML)
public Response consumeXML( Student student ) {
String output = student.toString();
return Response.status(200).entity(output).build();
}
}
Now REst Jersey Client:
现在休息泽西岛客户:
public static void main(String[] args) {
try {
Student student = new Student();
student.setName("JON");
student.setAddress("Paris");
student.setId(5);
String resturl = "http://localhost:8080/RestJerseyClientXML/rest/StudentService/update";
Client client = Client.create();
WebResource webResource = client.resource(resturl);
ClientResponse response = webResource.accept("application/xml")
.post(ClientResponse.class, student);
String output = response.getEntity(String.class);
System.out.println("Server response : " + response.getStatus());
System.out.println();
System.out.println(output);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
} catch (Exception e) {
}
}