简体   繁体   中英

How to stop jersey client from throwing exception on Http 301?

I am using the Jersey client to run some integration tests against my service. However, one of my calls sends a redirect. I am expecting to get a redirect but when Jersey Client gets the redirect it errors out with a com.sun.jersey.api.client.UniformInterfaceException. Is there some way to make it accept the response with the redirect and just let me know what it got?

You can catch UniformInterfaceException which provides response field containing all the details.

You could additionally write some hamcrest matchers to express your expectations:

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;
    }

}

Also note that follow redirects (in setUp method) should be set to false in order to get UniformInterfaceException instead of following redirect (if one is specified in Location header).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM