无法使用基于Jersey的客户端进行REST调用



我有一个基于Jersey的REST客户端和一个定义如下的GET调用:

在调用client.get((之后,代码不会出现。在client.get((调用中出现空指针异常,这是调用REST客户端的类的初始化逻辑:

Student.java:

public class Student {
private static RestClient client;
@SuppressWarnings("static-access")
public Student(Client client) {
this.client = new RestClient(client, "xyz");
}
public static RestClient getClient() {
return client;
}
public static void addStudent() throws Exception {
try {       
String addStudentUri = "https://www.zebapi.com/api/v1/market/ticker-new/btc/inr";     
ClientResponse js_response = getClient().get(URI.create(addStudentUri));
String s = js_response.getEntity(String.class);
System.out.println(s);
} catch (Exception e) {
System.out.println(e);          
}
}
public static void main(String[] args) {
try {
addStudent();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

RestClient.java

public class RestClient {
private Client client;
private String randomHeader = "";
public RestClient(Client jerseyClient) {
this.client = jerseyClient;
}
public RestClient(Client jerseyClient, String random) {
this.client = jerseyClient;
this.randomHeader = random;
}
public String getRandomHeader() {
return randomHeader;
}
public void setRandomHeader(String randomHeader) {
this.randomHeader = randomHeader;
}
public RestClient() {
}
public ClientResponse get(URI uri)
{
return client.resource(uri)
.get(ClientResponse.class);
}
public ClientResponse post(URI uri)
{
return client.resource(uri)
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class);
}
}

你能帮忙吗?

您从未初始化过client,这就是您获得NPE的原因;您正试图使用一个尚未初始化的对象。

您应该做的是从所有方法和client字段中删除所有static修饰符;除了CCD_ 4方法之外的所有方法。然后在main方法中,创建一个新的Student,传入一个新Client。然后使用该Student实例来调用addStudent()方法。

public class Student {
private RestClient client;
public Student(Client client) {
this.client = new RestClient(client, "xyz");
}
public RestClient getClient() {
return this.client;
}
public void addStudent() {}
public static void main(String...args) {
new Student(Client.create()).addStudent();
// or a more verbose way
Client jerseyClient = Client.create();
Student student = new Student(jerseyClient);
student.addStudent();
}
}

我将其标记为Community Wiki,因为实际上它应该标记为What is a NullPointerException的副本,我该如何修复它?。在Stack Overflow中,Is已经成为标准做法,当一个问题是关于一个易于修复的NullPointerException时,我们应该将该问题作为该链接问题的副本关闭。

如果NullPointerException是由我们开发人员编写的代码引起的,那么它通常很容易修复。能够检测并修复这一点应该是微不足道的。因此,请复习链接的问题,以便下次可以自己处理此类问题。

最新更新