我编写了简单的REST Web服务客户端类,它使用JAX-RS 2.0客户端API来发出REST请求.我试图弄清楚如何为每次调用设置请求超时.以下是请求的代码:
Client client = ClientBuilder.newBuilder().build();
WebTarget resourceTarget = client.target(restServiceUrl)
.path("{regsysID}/{appointmentID}/")
.resolveTemplate("regsysID", regSysId)
.resolveTemplate("appointmentID", apptId);
Invocation invocation = resourceTarget.request(MediaType.APPLICATION_JSON).buildPut(null);
String createSessionJson = invocation.invoke(String.class);
Run Code Online (Sandbox Code Playgroud)
小智 24
注意:这是JAX-RS 2.1上提供的新方法
这是一个非常古老的帖子,但下面的代码将适用于球衣和resteasy.
ClientBuilder clientBuilder = ClientBuilder.newBuilder();
clientBuilder.connectTimeout(10, TimeUnit.SECONDS);
clientBuilder.readTimeout(12, TimeUnit.SECONDS);
Client client = clientBuilder.build();
Run Code Online (Sandbox Code Playgroud)
Jer*_*oen 18
您可以通过首先创建ClientConfig并在创建新客户端时将其作为参数提供来完成此操作.
import org.glassfish.jersey.client.ClientProperties;
ClientConfig configuration = new ClientConfig();
configuration.property(ClientProperties.CONNECT_TIMEOUT, 1000);
configuration.property(ClientProperties.READ_TIMEOUT, 1000);
Client client = ClientBuilder.newClient(configuration);
Run Code Online (Sandbox Code Playgroud)
cod*_*rum 12
使用Resteasy,可以通过构建您的客户端来实现.
Client client = new ResteasyClientBuilder()
.establishConnectionTimeout(2, TimeUnit.SECONDS)
.socketTimeout(2, TimeUnit.SECONDS)
.build();
Run Code Online (Sandbox Code Playgroud)
我还没有看到您可以设置的标准配置属性列表,通过ClientBuilder.newClient(Configuration configuration)这些属性可以使这个可移植.
首先,您必须添加相关的依赖项(这是WildFly 10.1的):
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.14.Final</version>
<scope>provided</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
接下来-创建一个普通的Apache HttpClient并使用覆盖一个方法将其推送给RestEasy Enginge,这将导致问题:
// create here a normal Apache HttpClient with all parameters, that you need
HttpClient httpClient = createHttpClient(connectTimeout,
socketTimeout,
connectionRequestTimeout,
maxTotalHTTPConnections);
// Deprecated Apache classes cleanup https://issues.jboss.org/browse/RESTEASY-1357
// Client Framework not honoring connection timeouts Apache Client 4.3 https://issues.jboss.org/browse/RESTEASY-975
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient) {
@Override
protected void loadHttpMethod(ClientInvocation request, HttpRequestBase httpMethod) throws Exception {
super.loadHttpMethod(request, httpMethod);
httpMethod.setParams(new BasicHttpParams());
}
};
return new ResteasyClientBuilder().httpEngine(engine).build();
Run Code Online (Sandbox Code Playgroud)
看一下https://issues.jboss.org/browse/RESTEASY-975似乎该问题已在3.1.0.Final版本中解决。
| 归档时间: |
|
| 查看次数: |
35020 次 |
| 最近记录: |