gpt4 book ai didi

java - 调用rest api客户端

转载 作者:行者123 更新时间:2023-12-02 13:33:09 25 4
gpt4 key购买 nike

我在 Eclipse 中创建了一个 REST API 作为 Maven 项目。Rest api 的 MobileAnalyticsModel 类是

package org.subhayya.amazonws.mobileanalytics;

import java.util.Date;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class MobileAnalyticsModel {

private String name;
private Date created;
private String location;
private String prize;
private String requirement;

public MobileAnalyticsModel() {

}
public MobileAnalyticsModel(String name, String location, String prize, String requirement) {

this.name = name;
this.location = location;
this.prize = prize;
this.requirement = requirement;
this.created = new Date();
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Date getCreated() {
return created;
}

public void setCreated(Date created) {
this.created = created;
}

public String getLocation() {
return location;
}

public void setLocation(String location) {
this.location = location;
}

public String getPrize() {
return prize;
}

public void setPrize(String prize) {
this.prize = prize;
}

public String getRequirement() {
return requirement;
}

public void setRequirement(String requirement) {
this.requirement = requirement;
}
}

这是创建的 api 的 json 响应:

this is the json response of the created api

和这是我调用 REST API 的示例测试代码:

package org.subhayya.example;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;

public class SampleTestREstClient {

public static void main(String[] args) {


Client client = ClientBuilder.newClient( );
String reponse = client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
.request(MediaType.APPLICATION_JSON)
.get(String.class);

System.out.println(reponse);
}}

然后我得到了完整的 json 响应..如

 [{"created":"2017-03-30T14:36:58.56","location":"http://api.server.com","name":"Mobile Analytics","prize":"$1.00 per 1,000,000 Amazon Mobile Analytics events per month thereafter","requirement":"PutEvents"}]

但我希望将单个参数作为我的输出,例如名称、位置或要求。我也在同一个 Maven 项目中创建客户端调用代码。所以我写了如下代码

Client client = ClientBuilder.newClient( );
MobileAnalyticsModel reponse =
client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
.request(MediaType.APPLICATION_JSON)
.get(MobileAnalyticsModel.class);

System.out.println(reponse.getName());

但是我遇到了异常,所以我将其更改为System.out.println(reponse);)至少得到 JSON 响应,然后也会得到错误。

console view

如何从 JSON 响应中获取单个名称参数?我是这个rest api的新手。请帮助我尽快解决这个问题。提前致谢

最佳答案

您的响应是一个字符串。访问 JSON 响应元素的最简单方法是将响应转换为 Json 对象。然后您可以通过字段的名称轻松访问这些字段。看一下: How to parse JSON in Java

关于java - 调用rest api客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43113530/

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