【问题标题】:How to stop jersey client from throwing exception on Http 301?如何阻止球衣客户端在 Http 301 上抛出异常?
【发布时间】:2012-10-26 05:41:59
【问题描述】:

我正在使用 Jersey 客户端针对我的服务运行一些集成测试。但是,我的一个电话发送了重定向。我期待获得重定向,但是当泽西客户端获得重定向时,它会出现 com.sun.jersey.api.client.UniformInterfaceException 错误。有没有办法让它接受重定向的响应,让我知道它得到了什么?

【问题讨论】:

  • 你解决了吗?
  • 如果将实体类型设置为 ClientResponse 而不是 String 等,则不会出现异常。然后,您可以阅读响应代码并自己发出新请求。我还没有找到透明的方法

标签: java jersey jersey-client


【解决方案1】:

您可以捕获 UniformInterfaceException,它提供包含所有详细信息的响应字段。

您还可以编写一些 hamcrest 匹配器来表达您的期望:

import static javax.ws.rs.core.Response.Status.*;
import static org.junit.rules.ExpectedException.*;

import javax.ws.rs.core.Response.Status;

import org.hamcrest.*;
import org.junit.*;
import org.junit.rules.ExpectedException;

import com.sun.jersey.api.client.*;

public class MyResourceShould {

    @Rule
    public ExpectedException unsuccessfulResponse = none();

    private WebResource resource;

    @Before
    public void setUp() {
        Client client = Client.create();
        client.setFollowRedirects(false);
        resource = client.resource("http://example.com");
    }

    @Test
    public void reportMovedPermanently() {
        unsuccessfulResponse.expect(statusCode(MOVED_PERMANENTLY));

        resource.path("redirecting").get(String.class);
    }

    public static Matcher<UniformInterfaceException> statusCode(Status status) {
        return new UniformInterfaceExceptionResponseStatusMatcher(status);
    }

}

class UniformInterfaceExceptionResponseStatusMatcher extends TypeSafeMatcher<UniformInterfaceException> {

    private final int statusCode;

    public UniformInterfaceExceptionResponseStatusMatcher(Status status) {
        this.statusCode = status.getStatusCode();
    }

    public void describeTo(Description description) {
        description.appendText("response with status ").appendValue(statusCode);
    }

    @Override
    protected boolean matchesSafely(UniformInterfaceException exception) {
        return exception.getResponse().getStatus() == statusCode;
    }

}

另请注意,跟随重定向(在 setUp 方法中)应设置为 false 以获取 UniformInterfaceException 而不是跟随重定向(如果在 Location 标头中指定)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 2016-06-24
    相关资源
    最近更新 更多