如何使用jax -rs创建POST请求

时间:2019-06-11 09:09:48

标签: java json rest web-services jax-rs

我有两个类PlaylistResource,它具有一个createPlaylist方法,该方法接受一个PlaylistRequest类型的对象。我想在localhost:9999 / playlists上创建一个POST请求,而我正在使用Postman,但不确定如何将PlaylistRequest对象(该请求是请求)传递给方法createPlaylist。

@XmlType(propOrder= {"title", "artistSeeds", "numberOfSongs"})
@XmlAccessorType(XmlAccessType.FIELD)
public class PlaylistRequest {

    private String title = "";
    @XmlElement(name = "seeds")
    private List<String> artistSeeds;
    @XmlElement (name = "size")
    private int numberOfSongs = 0;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<String> getArtistSeeds() {
        return artistSeeds;
    }

    public void setArtistSeeds(List<String> artistSeeds) {
        this.artistSeeds = artistSeeds;
    }

    public int getNumberOfSongs() {
        return numberOfSongs;
    }

    public void setNumberOfSongs(int numberOfSongs) {
        this.numberOfSongs = numberOfSongs;
    }
}

另一堂课

@Path("playlists")
public class PlaylistResource implements PlaylistApi {

    @Override
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response createPlaylist(PlaylistRequest request) {

        if(request == null) {
            System.out.println("Was here");
            throw new ClientRequestException(new ErrorMessage("no parameter passed."));
        }

        try {
            List<Song> playList = new ArrayList<>();
            List<Song> songs = new ArrayList<>();
            List<String> artistsIds = new ArrayList<>();
            ArtistResource artistsResources = new ArtistResource();
            int playlistDefaultSize = 10;

            int i = 0;
            do {
                playList.add(songs.get(i));
                i++;
            }while( i < playlistDefaultSize);

            Playlist playlist = new Playlist();
            playlist.setTitle(request.getTitle());
            playlist.setSize(songs.size());
            playlist.setTracks(playList);

            return Response.status(Response.Status.CREATED.getStatusCode()).entity(playlist).build();
        } catch (Exception e) {
            throw new RemoteApiException(new ErrorMessage(e.getMessage()));
        }
    }

}

2 个答案:

答案 0 :(得分:0)

只需在请求的JSON中添加一个Body对象,在Raw Json中选择Postman并粘贴以下对象:

注意:在请求的Content-Type中添加密钥application/json并将其值设置为Header

{
  "title": "Some title",
  "artistSeeds": [
    "string1",
    "string2"
  ],
  "numberOfSongs": 0
}

HEADER Header 身体 Body

答案 1 :(得分:0)

将此参数从数据类更改为字符串,

public Response createPlaylist(PlaylistRequest request) {

public Response createPlaylist(String request) {

然后使用GSON将其转换为数据类。

PlaylistRequest request = new Gson().fromJson(request, new TypeToken<PlaylistRequest >(){}.getType());