在RESTEasy中使用POST请求

问题描述 投票:3回答:1

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

veb.hml

<?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.hml

<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类

(student.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服务生成和使用JSON输出

rest easy JSON services.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();

}
}

rest easy client.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网址是http://localhost:8080/RESTEasyJSONExample/rest/jsonresponse/send时,我没有得到任何响应。我使用的是正确的网址吗?我哪里做错了?我的总体目的是使用JSON或XML实现POST方法,而不使用任何REST Client工具,如POSTMAN。

java json rest maven resteasy
1个回答
0
投票

我已经使用Jersey客户发布请求。我能够发布XML数据。这应该适用于Json。请参考如何构建REST客户端:http://entityclass.in/rest/jerseyClientGetXml.htm

REST服务

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

现在REst 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) {

        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.