gpt4 book ai didi

java - 在 RESTEasy 中使用 POST 请求

转载 作者:行者123 更新时间:2023-12-01 04:59:51 27 4
gpt4 key购买 nike

早些时候,我使用 POSTMAN 工具提交 GET/PUT/POST/DELETE 但现在我正在尝试在不使用任何 REST API 客户端的情况下实现 POST 操作。为此,我提到了
this website .
我创建了一个 Maven 项目,这些是我的示例代码:

网页.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
<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-jackson-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>

要表示为 JSON 的 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();
}

}

用于生成和使用 JSON 输出的 REST 服务

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
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();

}

}
}

现在,每当我使用 GET url 时,我都会得到输出:
http://localhost:8080/RESTEasyJSONExample/rest/jsonresponse/print/James

这基本上用于生成 JSON,但是当我使用 POST url 时,它是 http://localhost:8080/RESTEasyJSONExample/rest/jsonresponse/send我没有得到任何回应。我是否使用了正确的 URL?我哪里做错了?我的总体目的是使用 JSON 或 XML 实现 POST 方法,而不使用任何像 POSTMAN 这样的 REST 客户端工具。

最佳答案

嗨,我已使用 Jersey 客户端发布请求。
我能够发布 XML 数据。
这也应该适用于 Json。
REST Client搭建请引用:http://entityclass.in/rest/jerseyClientGetXml.htm

休息服务

@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();
}
}

现在休息 Jersey 客户:
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) {

}
}

关于java - 在 RESTEasy 中使用 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33991559/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com