标签: java-http-client

尝试在Eclipse Oxygen中的Java中使用jdk.incubator.http.HttpClient时出现NoClassDefFoundError

这是我使用的代码片段:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://www.google.com")).GET().build();
HttpResponse.BodyHandler responseBodyHandler = HttpResponse.BodyHandler.asString();
HttpResponse response = client.send(request, responseBodyHandler);
System.out.println("Status code = " + response.statusCode());

String body = response.body().toString();
System.out.println(body);
Run Code Online (Sandbox Code Playgroud)

NoClassDefFoundError当我运行上面的代码时,Eclipse抛出HttpClient。但是,当我将与一起使用时,此功能可以完美--add-modules=jdk.incubator.httpclient。怎样才能使代码通过Eclipse执行?

java eclipse http2 jshell java-http-client

5
推荐指数
1
解决办法
808
查看次数

在 GZIPInputStream 中包装 BodySubscriber<InputStream> 会导致挂起

我正在使用新java.net.http类来处理异步 HTTP 请求+响应交换,并且我正在尝试找到一种方法让 BodySubscriber 处理不同的编码类型(例如 gzip)。

但是,映射 aBodySubsriber<InputStream>以使底层流被 a 包装GZIPInputStream(当在响应标头中找到“Content-Encoding:gzip”时)会导致挂起。没有例外,只是完全停止活动。

映射的代码BodySubscriber如下所示:

private HttpResponse.BodySubscriber<InputStream> gzippedBodySubscriber(
        HttpResponse.ResponseInfo responseInfo) {
    return HttpResponse.BodySubscribers.mapping(
            HttpResponse.BodySubscribers.ofInputStream(),
            this::decodeGzipStream);
}

private InputStream decodeGzipStream(InputStream gzippedStream) {
    System.out.println("Entered decodeGzipStream method.");
    try {
        InputStream decodedStream = new GZIPInputStream(gzippedStream);
        System.out.println(
                "Created GZIPInputStream to handle response body stream.");
        return decodedStream;
    } catch (IOException ex) {
        System.out.println("IOException occurred while trying to create GZIPInputStream.");
        throw new UncheckedIOException(ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

接收到具有“gzip”编码的 HTTP 响应会导致控制台显示以下内容:

进入EncodedBodyHandler.apply方法。
进入decodeGzipStream方法。

没有看到更多内容,因此调用GZIPInputStream构造函数之后的行永远不会执行。 …

java gzipinputstream java-http-client

5
推荐指数
1
解决办法
1390
查看次数

如何在 Java 11 http 客户端中保持连接活动

我正在使用HttpClient带有 HTTP/2的 Java 11 ,需要保持连接活动几分钟,但构建器没有设置它的选项。有没有办法指定这一点并使客户端保持连接活动一段时间?

java http2 java-http-client java-11

5
推荐指数
2
解决办法
6034
查看次数

与HttpClient的状态为CLOSE_WAIT的连接泄漏

We are using JDK11 java.net.http HTTP client to get data from an API. After we receive the response the connections remain opened in our server with TCP state CLOSE_WAIT, which means the client must close the connection.

From RFC 793 terminology:

CLOSE-WAIT - represents waiting for a connection termination request from the local user.

This is our client code which runs on WildFly 16 running on Java 12 as a stateless REST API. We don't understand why this is …

java connection-leaks java-http-client java-11

5
推荐指数
1
解决办法
971
查看次数

Java 11:新的HTTP客户端发送带有x-www-form-urlencoded参数的POST请求

我正在尝试使用新的http客户端api发送POST请求。是否有内置的方式发送格式为的参数x-www-form-urlencoded

我当前的代码:

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(url))
        .header("Content-Type", "application/x-www-form-urlencoded")
        .POST(BodyPublishers.ofString("a=get_account&account=" + URLEncoder.encode(account, "UTF-8")))
        .build();
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种传递参数的更好方法。像这样:

Params p=new Params();
p.add("a","get_account");
p.add("account",account);
Run Code Online (Sandbox Code Playgroud)

我需要自己构建此功能还是已经内置了某些功能?

我正在使用Java 12。

java java-http-client

5
推荐指数
2
解决办法
2481
查看次数

如何使用Java 11 HttpClient和Jackson将JSON响应映射到Java类?

我是Java 11 HttpClient的新手,想尝试一下。我有一个简单的GET请求,该请求返回JSON,我想将JSON响应映射到名为的Java类Questionnaire

我知道我可以将响应立即转换为String或类似这样的输入流

HttpRequest request = HttpRequest.newBuilder(new URI(String.format("%s%s", this.baseURI, "/state")))
          .header(ACCEPT, APPLICATION_JSON)
          .PUT(noBody()).build();

HttpResponse<String> response = this.client.send(request, HttpResponse.BodyHandlers.ofString());
Run Code Online (Sandbox Code Playgroud)

我该如何写一些将JSON字符串转换为我的Questionnaire类的东西?

HttpResponse<Questionnaire> response = this.client.send(request, HttpResponse.BodyHandlers./* what can I do here? */);
Run Code Online (Sandbox Code Playgroud)

我使用Jackson将JSON转换为Java类实例。Jackson是否支持新的Java标准HttpClient?

更新1 我不够精确,对此感到抱歉。我正在寻找一个阻止获取示例。我知道http://openjdk.java.net/groups/net/httpclient/recipes.html#jsonGet

java http httpclient java-http-client java-11

5
推荐指数
2
解决办法
276
查看次数

java.net.HttpClient 状态为 CLOSE_WAIT 的连接泄漏

我们使用 openJDK11.0.6 java.net.http HTTP (HTTP1.1) 客户端从网站获取内容。经过长时间的执行,我们注意到性能下降。即使应用程序不执行任何操作,CPU 也会 100% 使用。我们能够确定它来自大量应用程序泄漏的套接字(CLOSE-WAIT 状态)。

这里已经有一些关于它的问题(比如这个),但是所有提交的错误都应该被修复并反向移植到 java 11.0.6。

我已经能够将该错误重现到github 上的一个 minalist 项目。似乎只有当客户端从服务器收到 204 NO-CONTENT 时才会发生这种情况。

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;

public class BasicFetcherApp {

  public static void main(String[] args) throws Exception {
    System.out.println("App is running... pid: " + ProcessHandle.current().pid());
    HttpClient client = HttpClient.newBuilder().version(Version.HTTP_1_1).build();
    for (int i = 0; i < 10; ++i) {
      HttpRequest request =
          HttpRequest.newBuilder(URI.create("http://localhost:4001/nocontent")).build();
      HttpResponse<String> response = client.send(request, BodyHandlers.ofString()); …
Run Code Online (Sandbox Code Playgroud)

java connection-leaks java-http-client java-11

5
推荐指数
1
解决办法
754
查看次数

java 11 HTTP 客户端上的“java.io.IOException:连接超时”VS HttpTimeoutException

我正在使用 Java 11 http-client ( java.net.http)。

send()方法声明了这些异常:

@throws IOException
@throws InterruptedException
@throws IllegalArgumentException
@throws SecurityException
Run Code Online (Sandbox Code Playgroud)

我对捕获超时引起的异常感兴趣。我认为最好的方法是抓住 HttpTimeoutException(扩展IOException

但是,我有时会看到,当发生超时时,引发的异常是:

java.io.IOException: Connection timed out
Run Code Online (Sandbox Code Playgroud)

现在我想知道:

  1. 为什么会抛出更一般的异常?
  2. 应该如何编写 catch 以确保捕获所有可能的超时相关异常?

java timeoutexception java-http-client java-11

5
推荐指数
1
解决办法
1251
查看次数

Kotlin 协程作用域:如果在控制器端点中使用 return@runBlocking 是否会出现问题

目的:我想编码一个端点,它利用轻量协程消耗另一个端点,假设我正在编码一个轻量异步端点客户端。

我的背景:第一次尝试使用 Kotlin Coroutine。我最近几天研究并四处寻找。我发现很多文章解释如何在 Android 中使用 Coroutine,但很少有其他文章解释如何在主函数中使用 Coroutine。不幸的是,我没有找到解释如何使用协程编写控制器端点的文章,如果我正在做一些不推荐的事情,它就会在我的脑海中敲响警钟。

目前情况:我使用协程成功创建了几种方法,但我想知道哪种方法最适合传统的 GET。最重要的是,我想知道如何正确处理异常。

主要问题:推荐以下方法中的哪一种以及我应该关注哪种异常处理?

相关的第二个问题:有什么区别

fun someMethodWithRunBlocking(): String? = runBlocking {
 return@runBlocking ...
}
Run Code Online (Sandbox Code Playgroud)

suspend fun someMethodWithSuspendModifier(): String?{
  return ...
}
Run Code Online (Sandbox Code Playgroud)

下面的所有尝试都在工作并返回 json 响应,但我不知道端点方法上的“runBlocking”和返回“return@runBlocking”是否会给我带来一些负面的缺点。

控制器(端点)

package com.tolearn.controller

import com.tolearn.service.DemoService
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.*
import kotlinx.coroutines.runBlocking
import java.net.http.HttpResponse
import javax.inject.Inject

@Controller("/tolearn")
class DemoController {

    @Inject
    lateinit var demoService: DemoService

    //APPROACH 1:
    //EndPoint method with runBlocking CoroutineScope
    //Using Deferred.await
    //Using return@runBlocking
    @Get("/test1")
    @Produces(MediaType.TEXT_PLAIN)
    fun getWithRunBlockingAndDeferred(): String? …
Run Code Online (Sandbox Code Playgroud)

kotlin java-http-client java-11 kotlin-coroutines

5
推荐指数
1
解决办法
3993
查看次数

JDK 11 HttpClient:BindException:无法分配请求的地址

我正在使用 JDK 11 附带的新 HttpClient 发出许多请求(向 Github 的 API,但我认为这无关紧要),尤其是 GET。

对于每个请求,我构建并使用一个 HttpClient,如下所示:

final ExecutorService executor = Executors.newSingleThreadExecutor();
final HttpClient client = client = HttpClient
    .newBuilder()
    .followRedirects(HttpClient.Redirect.NORMAL)
    .connectTimeout(Duration.ofSeconds(10))
    .executor(executor)
    .build();
try {
   //send request and return parsed response;
} finally {
   //manually close the specified executor because HttpClient doesn't implement Closeable,
   //so I'm not sure when it will release resources.
   executor.shutdownNow();
}
Run Code Online (Sandbox Code Playgroud)

这似乎工作正常,除了时不时地,我收到以下异常,并且请求将不再有效,直到我重新启动应用程序:

Caused by: java.net.ConnectException: Cannot assign requested address
...
Caused by: java.net.BindException: Cannot assign requested address
    at java.base/sun.nio.ch.Net.connect0(Native Method) …
Run Code Online (Sandbox Code Playgroud)

http java-http-client java-11 openjdk-11

5
推荐指数
1
解决办法
1353
查看次数