这是Java代码:
package com.company;
import java.io.IOException;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
public class Main {
static String sURL = "http://speller.yandex.net/services/spellservice";
public static void main(String[] args) throws IOException {
CloseableHttpResponse resp1 = null;
try{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(sURL + "/checkText?text=мошына");
resp1 = httpClient.execute(httpGet);
System.out.println(EntityUtils.toString(resp1.getEntity()));
} catch (IOException | ParseException e){
e.printStackTrace();
} finally {
try {
resp1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
错误:
Exception in thread "main" java.lang.NullPointerException
at com.company.Main.main(Main.java:24)
如何修复此错误?
在第 24 行,如果捕获成功,则调用其值为 null 的对象 (resp1) 的 close() 方法。
执行以下操作: