嗨,任何人都可以看看:
当我尝试使用VERTX HTTP CLIENT获取数据时,它在最后一行给出了空指针异常,并且当我使用java HTTP CLIENT时,相同的URL提供数据:
HttpClientOptions options = new HttpClientOptions().setKeepAlive(false);
options.setLogActivity(true);
options.setDefaultHost("http://delvmpllbbab10");
options.setDefaultPort(7003);
HttpClient client = vertx.createHttpClient(options);
HttpClientResponse[] clientResponse = {null};
client.request(HttpMethod.GET, "/rcsservices/homePage", response -> {
System.out.println("Received response with status code " + response.statusCode());
clientResponse[0] = response;
}).putHeader("content-type", "application/json").end(clientResponse[0].toString());
这段代码我有些问题......
答案 0 :(得分:0)
这是正确的,您将获得NPE
,因此在您的代码中,您使用clientResponse
初始化{ null }
变量。如果您现在按照代码的执行方式进行操作,您将看到原因:
client.request(
putHeader(...)
end(clientResponse[0].toString())
现在您看到clientResponse[0]
仍为空(这是您初始化它的值。所以发生的是您正在调用:
null.toString()
哪个无效,将始终抛出Null Pointer Exception
。
答案 1 :(得分:0)
我遇到了与开始使用Vert-X框架相同的问题,我可以从代码中注意到以下改进:
.end()
包含新的"客户请求正文"但是当你进行GET时,正文必须为空HttpHeaders
和MediaType
(我个人使用JAX-RS中的MediaType
)而不是编写自己的字符串。System.out.println(...)
以下代码显示了我如何设置将响应返回给原始调用者:
public void callWebService(@Context HttpServerRequest request, @Suspended final AsyncResponse asyncResponse) {
HttpClientOptions options = new HttpClientOptions().setKeepAlive(false);
options.setLogActivity(true);
options.setDefaultHost("http://delvmpllbbab10");
options.setDefaultPort(7003);
HttpClient client = vertx.createHttpClient(options);
client.request(HttpMethod.GET, "/rcsservices/homePage", response -> {
System.out.println("Received response with status code " + response.statusCode());
int code = response.statusCode();
if (code == 200) {
response.bodyHandler(bufferResponse -> {
// Adapt according your response type, could be String as well
JsonObject httpResult = bufferResponse.toJsonObject();
System.out.println("Received HTTP response with body " + httpResult);
asyncResponse.resume(Response.ok(httpResult).build());
});
} else {
response.bodyHandler(bufferResponse -> {
// Return null in a JSON Object in case of error
String httpResult = "{null}";
asyncResponse.resume(Response.status(code).entity(httpResult).build());
});
}
}).putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).end();
有很多方法可以做同样的事情,你可以查看official manual page。