gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:35:47 25 4
gpt4 key购买 nike

我有两个类 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()));
}
}

}

最佳答案

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

公共(public)响应createPlaylist(PlaylistRequest请求){

公共(public)响应createPlaylist(字符串请求){

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

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

关于java - 如何使用 jax -rs 创建 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56540209/

25 4 0
文章推荐: java - 如何向数组列表中的现有元素添加信息?
文章推荐: css - 根据内容宽度将背景颜色应用于宽度
文章推荐: java - 无法禁用远程 Spring Boot JMX 访问
文章推荐: css - % 这个
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com