- 已关闭。**此问题需要debugging details。当前不接受答案。
编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
2小时前关门了。
Improve this question
使用纯Java,我尝试发送Get请求并得到响应null。我的代码中是否有任何bug?
public static void TradeExchange() throws IOException, InterruptedException {
String urlString = "https://api.spimex.com/otc/lookup-tables/1";
HttpClient httpClient = new HttpClient() {
@Override
public Optional<CookieHandler> cookieHandler() {
return Optional.empty();
}
@Override
public Optional<Duration> connectTimeout() {
return Optional.empty();
}
@Override
public Redirect followRedirects() {
return null;
}
@Override
public Optional<ProxySelector> proxy() {
return Optional.empty();
}
@Override
public SSLContext sslContext() {
return null;
}
@Override
public SSLParameters sslParameters() {
return null;
}
@Override
public Optional<Authenticator> authenticator() {
return Optional.empty();
}
@Override
public Version version() {
return null;
}
@Override
public Optional<Executor> executor() {
return Optional.empty();
}
@Override
public <T> HttpResponse<T> send(HttpRequest httpRequest, HttpResponse.BodyHandler<T> bodyHandler) throws IOException, InterruptedException {
return null;
}
@Override
public <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest httpRequest, HttpResponse.BodyHandler<T> bodyHandler) {
return null;
}
@Override
public <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest httpRequest, HttpResponse.BodyHandler<T> bodyHandler, HttpResponse.PushPromiseHandler<T> pushPromiseHandler) {
return null;
}
};
HttpRequest httpRequest = HttpRequest.newBuilder(URI.create(urlString))
.GET()
.build();
try {
HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
String body = response.body();
} catch (IOException | InterruptedException e) {
System.out.println(e.getMessage());
}
}
3条答案
按热度按时间63lcw9qa1#
我不知道为什么您要用返回null和空选项的方法实现自己的HttpClient,并期望它能正常工作。
Java已经有了一个Http客户端的实现,你只需要使用它。
或使用助洗剂:
Examples from official docs
An article which covers how to use Java HttpClient
tcomlyy62#
你可以做类似的事情,你的代码返回null,因为你没有为你的HTTP客户端提供任何实现。
q3qa4bjr3#
您不应该实现自己的返回空值的HttpClient,您可以尝试以下操作: