feign.Request.HttpMethod Java Examples

The following examples show how to use feign.Request.HttpMethod. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RequestTemplate.java    From feign with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new Request Template.
 *
 * @param fragment part of the request uri.
 * @param target for the template.
 * @param uriTemplate for the template.
 * @param bodyTemplate for the template, may be {@literal null}
 * @param method of the request.
 * @param charset for the request.
 * @param body of the request, may be {@literal null}
 * @param decodeSlash if the request uri should encode slash characters.
 * @param collectionFormat when expanding collection based variables.
 * @param feignTarget this template is targeted for.
 * @param methodMetadata containing a reference to the method this template is built from.
 */
private RequestTemplate(String target,
    String fragment,
    UriTemplate uriTemplate,
    BodyTemplate bodyTemplate,
    HttpMethod method,
    Charset charset,
    Request.Body body,
    boolean decodeSlash,
    CollectionFormat collectionFormat,
    MethodMetadata methodMetadata,
    Target<?> feignTarget) {
  this.target = target;
  this.fragment = fragment;
  this.uriTemplate = uriTemplate;
  this.bodyTemplate = bodyTemplate;
  this.method = method;
  this.charset = charset;
  this.body = body;
  this.decodeSlash = decodeSlash;
  this.collectionFormat =
      (collectionFormat != null) ? collectionFormat : CollectionFormat.EXPLODED;
  this.methodMetadata = methodMetadata;
  this.feignTarget = feignTarget;
}
 
Example #2
Source File: FeignUnderAsyncTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void whenReturnTypeIsResponseNoErrorHandling() {
  Map<String, Collection<String>> headers = new LinkedHashMap<>();
  headers.put("Location", Collections.singletonList("http://bar.com"));
  final Response response = Response.builder()
      .status(302)
      .reason("Found")
      .headers(headers)
      .request(Request.create(HttpMethod.GET, "/", Collections.emptyMap(), null, Util.UTF_8))
      .body(new byte[0])
      .build();

  ExecutorService execs = Executors.newSingleThreadExecutor();

  // fake client as Client.Default follows redirects.
  TestInterface api = AsyncFeign.<Void>asyncBuilder()
      .client(new AsyncClient.Default<>((request, options) -> response, execs))
      .target(TestInterface.class, "http://localhost:" + server.getPort());

  assertEquals(api.response().headers().get("Location"),
      Collections.singletonList("http://bar.com"));

  execs.shutdown();
}
 
Example #3
Source File: JAXBCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void decodesXml() throws Exception {
  MockObject mock = new MockObject();
  mock.value = "Test";

  String mockXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mockObject>"
      + "<value>Test</value></mockObject>";

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(mockXml, UTF_8)
      .build();

  JAXBDecoder decoder = new JAXBDecoder(new JAXBContextFactory.Builder().build());

  assertEquals(mock, decoder.decode(response, MockObject.class));
}
 
Example #4
Source File: DefaultErrorDecoderTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void throwsFeignExceptionIncludingBody() throws Throwable {
  Response response = Response.builder()
      .status(500)
      .reason("Internal server error")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(headers)
      .body("hello world", UTF_8)
      .build();

  try {
    throw errorDecoder.decode("Service#foo()", response);
  } catch (FeignException e) {
    assertThat(e.getMessage())
        .isEqualTo(
            "[500 Internal server error] during [GET] to [/api] [Service#foo()]: [hello world]");
    assertThat(e.contentUTF8()).isEqualTo("hello world");
  }
}
 
Example #5
Source File: AsyncApacheHttp5ClientTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void whenReturnTypeIsResponseNoErrorHandling() throws Throwable {
  final Map<String, Collection<String>> headers = new LinkedHashMap<String, Collection<String>>();
  headers.put("Location", Arrays.asList("http://bar.com"));
  final Response response = Response.builder().status(302).reason("Found").headers(headers)
      .request(Request.create(HttpMethod.GET, "/", Collections.emptyMap(), null, Util.UTF_8))
      .body(new byte[0]).build();

  final ExecutorService execs = Executors.newSingleThreadExecutor();

  // fake client as Client.Default follows redirects.
  final TestInterfaceAsync api = AsyncFeign.<Void>asyncBuilder()
      .client(new AsyncClient.Default<>((request, options) -> response, execs))
      .target(TestInterfaceAsync.class, "http://localhost:" + server.getPort());

  assertEquals(Collections.singletonList("http://bar.com"),
      unwrap(api.response()).headers().get("Location"));

  execs.shutdown();
}
 
Example #6
Source File: GsonCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void decodes() throws Exception {

  List<Zone> zones = new LinkedList<Zone>();
  zones.add(new Zone("denominator.io."));
  zones.add(new Zone("denominator.io.", "ABCD"));

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .headers(Collections.emptyMap())
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .body(zonesJson, UTF_8)
      .build();
  assertEquals(zones,
      new GsonDecoder().decode(response, new TypeToken<List<Zone>>() {}.getType()));
}
 
Example #7
Source File: GsonCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void customDecoder() throws Exception {
  GsonDecoder decoder = new GsonDecoder(Collections.singletonList(upperZone));

  List<Zone> zones = new LinkedList<>();
  zones.add(new Zone("DENOMINATOR.IO."));
  zones.add(new Zone("DENOMINATOR.IO.", "ABCD"));

  Response response =
      Response.builder()
          .status(200)
          .reason("OK")
          .headers(Collections.emptyMap())
          .request(
              Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
          .body(zonesJson, UTF_8)
          .build();
  assertEquals(zones, decoder.decode(response, new TypeToken<List<Zone>>() {}.getType()));
}
 
Example #8
Source File: StreamDecoderTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCloseIteratorWhenStreamClosed() throws IOException {
  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .headers(Collections.emptyMap())
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .body("", UTF_8)
      .build();

  TestCloseableIterator it = new TestCloseableIterator();
  StreamDecoder decoder = new StreamDecoder((r, t) -> it);

  try (Stream<?> stream =
      (Stream) decoder.decode(response, new TypeReference<Stream<String>>() {}.getType())) {
    assertThat(stream.collect(Collectors.toList())).hasSize(1);
    assertThat(it.called).isTrue();
  } finally {
    assertThat(it.closed).isTrue();
  }
}
 
Example #9
Source File: LBClientTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void testRibbonRequest() throws URISyntaxException {
  // test for RibbonRequest.toRequest()
  // the url has a query whose value is an encoded json string
  String urlWithEncodedJson = "http://test.feign.com/p?q=%7b%22a%22%3a1%7d";
  HttpMethod method = HttpMethod.GET;
  URI uri = new URI(urlWithEncodedJson);
  Map<String, Collection<String>> headers = new LinkedHashMap<String, Collection<String>>();
  // create a Request for recreating another Request by toRequest()
  Request requestOrigin =
      Request.create(method, uri.toASCIIString(), headers, null, Charset.forName("utf-8"));
  RibbonRequest ribbonRequest = new RibbonRequest(null, requestOrigin, uri);

  // use toRequest() recreate a Request
  Request requestRecreate = ribbonRequest.toRequest();

  // test that requestOrigin and requestRecreate are same except the header 'Content-Length'
  // ps, requestOrigin and requestRecreate won't be null
  assertThat(requestOrigin.toString())
      .contains(String.format("%s %s HTTP/1.1\n", method, urlWithEncodedJson));
  assertThat(requestRecreate.toString())
      .contains(String.format("%s %s HTTP/1.1\nContent-Length: 0\n", method, urlWithEncodedJson));
}
 
Example #10
Source File: FeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void whenReturnTypeIsResponseNoErrorHandling() {
  Map<String, Collection<String>> headers = new LinkedHashMap<>();
  headers.put("Location", Collections.singletonList("http://bar.com"));
  final Response response = Response.builder()
      .status(302)
      .reason("Found")
      .headers(headers)
      .request(Request.create(HttpMethod.GET, "/", Collections.emptyMap(), null, Util.UTF_8))
      .body(new byte[0])
      .build();

  // fake client as Client.Default follows redirects.
  TestInterface api = Feign.builder()
      .client((request, options) -> response)
      .target(TestInterface.class, "http://localhost:" + server.getPort());

  assertEquals(api.response().headers().get("Location"),
      Collections.singletonList("http://bar.com"));
}
 
Example #11
Source File: ResponseTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void headerValuesWithSameNameOnlyVaryingInCaseAreMerged() {
  Map<String, Collection<String>> headersMap = new LinkedHashMap<>();
  headersMap.put("Set-Cookie", Arrays.asList("Cookie-A=Value", "Cookie-B=Value"));
  headersMap.put("set-cookie", Collections.singletonList("Cookie-C=Value"));

  Response response = Response.builder()
      .status(200)
      .headers(headersMap)
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .body(new byte[0])
      .build();

  List<String> expectedHeaderValue =
      Arrays.asList("Cookie-A=Value", "Cookie-B=Value", "Cookie-C=Value");
  assertThat(response.headers()).containsOnly(entry(("set-cookie"), expectedHeaderValue));
}
 
Example #12
Source File: AsyncFeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void whenReturnTypeIsResponseNoErrorHandling() throws Throwable {
  Map<String, Collection<String>> headers = new LinkedHashMap<String, Collection<String>>();
  headers.put("Location", Arrays.asList("http://bar.com"));
  final Response response = Response.builder().status(302).reason("Found").headers(headers)
      .request(Request.create(HttpMethod.GET, "/", Collections.emptyMap(), null, Util.UTF_8))
      .body(new byte[0]).build();

  ExecutorService execs = Executors.newSingleThreadExecutor();

  // fake client as Client.Default follows redirects.
  TestInterfaceAsync api = AsyncFeign.<Void>asyncBuilder()
      .client(new AsyncClient.Default<>((request, options) -> response, execs))
      .target(TestInterfaceAsync.class, "http://localhost:" + server.getPort());

  assertEquals(Collections.singletonList("http://bar.com"),
      unwrap(api.response()).headers().get("Location"));

  execs.shutdown();
}
 
Example #13
Source File: JAXBCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void decodeAnnotatedParameterizedTypes() throws Exception {
  JAXBContextFactory jaxbContextFactory =
      new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build();

  Encoder encoder = new JAXBEncoder(jaxbContextFactory);

  Box<String> boxStr = new Box<>();
  boxStr.set("hello");
  Box<Box<String>> boxBoxStr = new Box<>();
  boxBoxStr.set(boxStr);
  RequestTemplate template = new RequestTemplate();
  encoder.encode(boxBoxStr, Box.class, template);

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.<String, Collection<String>>emptyMap())
      .body(template.body())
      .build();

  new JAXBDecoder(new JAXBContextFactory.Builder().build()).decode(response, Box.class);

}
 
Example #14
Source File: FeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void throwsRetryableExceptionIfNoUnderlyingCause() throws Exception {
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1"));
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 2"));

  String message = "play it again sam!";
  thrown.expect(RetryableException.class);
  thrown.expectMessage(message);

  TestInterface api = Feign.builder()
      .exceptionPropagationPolicy(UNWRAP)
      .retryer(new Retryer.Default(1, 1, 2))
      .errorDecoder(new ErrorDecoder() {
        @Override
        public Exception decode(String methodKey, Response response) {
          return new RetryableException(response.status(), message, HttpMethod.POST, null,
              response.request());
        }
      }).target(TestInterface.class, "http://localhost:" + server.getPort());

  api.post();
}
 
Example #15
Source File: SOAPFaultDecoderTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void soapDecoderThrowsSOAPFaultException() throws IOException {

  thrown.expect(SOAPFaultException.class);
  thrown.expectMessage("Processing error");

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(getResourceBytes("/samples/SOAP_1_2_FAULT.xml"))
      .build();

  new SOAPDecoder.Builder().withSOAPProtocol(SOAPConstants.SOAP_1_2_PROTOCOL)
      .withJAXBContextFactory(new JAXBContextFactory.Builder().build()).build()
      .decode(response, Object.class);
}
 
Example #16
Source File: SOAPFaultDecoderTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void errorDecoderReturnsFeignExceptionOn503Status() throws IOException {
  Response response = Response.builder()
      .status(503)
      .reason("Service Unavailable")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body("Service Unavailable", UTF_8)
      .build();

  Exception error =
      new SOAPErrorDecoder().decode("Service#foo()", response);

  Assertions.assertThat(error).isInstanceOf(FeignException.class)
      .hasMessage(
          "[503 Service Unavailable] during [GET] to [/api] [Service#foo()]: [Service Unavailable]");
}
 
Example #17
Source File: SOAPFaultDecoderTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void errorDecoderReturnsFeignExceptionOnEmptyFault() throws IOException {
  String responseBody = "<?xml version = '1.0' encoding = 'UTF-8'?>\n" +
      "<SOAP-ENV:Envelope\n" +
      "   xmlns:SOAP-ENV = \"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
      "   xmlns:xsi = \"http://www.w3.org/1999/XMLSchema-instance\"\n" +
      "   xmlns:xsd = \"http://www.w3.org/1999/XMLSchema\">\n" +
      "   <SOAP-ENV:Body>\n" +
      "   </SOAP-ENV:Body>\n" +
      "</SOAP-ENV:Envelope>";
  Response response = Response.builder()
      .status(500)
      .reason("Internal Server Error")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(responseBody, UTF_8)
      .build();

  Exception error =
      new SOAPErrorDecoder().decode("Service#foo()", response);

  Assertions.assertThat(error).isInstanceOf(FeignException.class)
      .hasMessage("[500 Internal Server Error] during [GET] to [/api] [Service#foo()]: ["
          + responseBody + "]");
}
 
Example #18
Source File: FeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void throwsOriginalExceptionAfterFailedRetries() throws Exception {
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1"));
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 2"));

  final String message = "the innerest";
  thrown.expect(TestInterfaceException.class);
  thrown.expectMessage(message);

  TestInterface api = Feign.builder()
      .exceptionPropagationPolicy(UNWRAP)
      .retryer(new Retryer.Default(1, 1, 2))
      .errorDecoder(new ErrorDecoder() {
        @Override
        public Exception decode(String methodKey, Response response) {
          return new RetryableException(response.status(), "play it again sam!", HttpMethod.POST,
              new TestInterfaceException(message), null, response.request());
        }
      }).target(TestInterface.class, "http://localhost:" + server.getPort());

  api.post();
}
 
Example #19
Source File: RequestTemplateTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void resolveTemplateWithBodyTemplateDoesNotDoubleDecode() {
  RequestTemplate template = new RequestTemplate().method(HttpMethod.POST)
      .bodyTemplate(
          "%7B\"customer_name\": \"{customer_name}\", \"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D",
          Util.UTF_8);

  template = template.resolve(
      mapOf(
          "customer_name", "netflix",
          "user_name", "denominator",
          "password", "abc+123%25d8"));

  assertThat(template)
      .hasBody(
          "{\"customer_name\": \"netflix\", \"user_name\": \"denominator\", \"password\": \"abc+123%25d8\"}");
}
 
Example #20
Source File: SOAPCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void decodeAnnotatedParameterizedTypes() throws Exception {
  JAXBContextFactory jaxbContextFactory =
      new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build();

  Encoder encoder = new SOAPEncoder(jaxbContextFactory);

  Box<String> boxStr = new Box<>();
  boxStr.set("hello");
  Box<Box<String>> boxBoxStr = new Box<>();
  boxBoxStr.set(boxStr);
  RequestTemplate template = new RequestTemplate();
  encoder.encode(boxBoxStr, Box.class, template);

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(template.body())
      .build();

  new SOAPDecoder(new JAXBContextFactory.Builder().build()).decode(response, Box.class);

}
 
Example #21
Source File: RequestTemplateTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void resolveTemplateWithBodyTemplateSetsBodyAndContentLength() {
  RequestTemplate template = new RequestTemplate().method(HttpMethod.POST)
      .bodyTemplate(
          "%7B\"customer_name\": \"{customer_name}\", \"user_name\": \"{user_name}\", " +
              "\"password\": \"{password}\"%7D",
          Util.UTF_8);

  template = template.resolve(
      mapOf(
          "customer_name", "netflix",
          "user_name", "denominator",
          "password", "password"));

  assertThat(template)
      .hasBody(
          "{\"customer_name\": \"netflix\", \"user_name\": \"denominator\", \"password\": \"password\"}")
      .hasHeaders(
          entry("Content-Length",
              Collections.singletonList(String.valueOf(template.body().length))));
}
 
Example #22
Source File: FeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
/**
 * when you must parse a 2xx status to determine if the operation succeeded or not.
 */
@Test
public void retryableExceptionInDecoder() throws Exception {
  server.enqueue(new MockResponse().setBody("retry!"));
  server.enqueue(new MockResponse().setBody("success!"));

  TestInterface api = new TestInterfaceBuilder()
      .decoder(new StringDecoder() {
        @Override
        public Object decode(Response response, Type type) throws IOException {
          String string = super.decode(response, type).toString();
          if ("retry!".equals(string)) {
            throw new RetryableException(response.status(), string, HttpMethod.POST, null,
                response.request());
          }
          return string;
        }
      }).target("http://localhost:" + server.getPort());

  assertEquals(api.post(), "success!");
  assertEquals(2, server.getRequestCount());
}
 
Example #23
Source File: RequestTemplateTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void insertHasQueryParams() {
  RequestTemplate template = new RequestTemplate().method(HttpMethod.GET)//
      .uri("/domains/1001/records")//
      .query("name", "denominator.io")//
      .query("type", "CNAME");

  template.target("https://host/v1.0/1234?provider=foo");

  assertThat(template)
      .hasPath("https://host/v1.0/1234/domains/1001/records")
      .hasQueries(
          entry("name", Collections.singletonList("denominator.io")),
          entry("type", Collections.singletonList("CNAME")),
          entry("provider", Collections.singletonList("foo")));
}
 
Example #24
Source File: JacksonCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void decodes() throws Exception {
  List<Zone> zones = new LinkedList<>();
  zones.add(new Zone("denominator.io."));
  zones.add(new Zone("denominator.io.", "ABCD"));

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(zonesJson, UTF_8)
      .build();
  assertEquals(zones,
      new JacksonDecoder().decode(response, new TypeReference<List<Zone>>() {}.getType()));
}
 
Example #25
Source File: JacksonCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void decodesIterator() throws Exception {
  List<Zone> zones = new LinkedList<Zone>();
  zones.add(new Zone("denominator.io."));
  zones.add(new Zone("denominator.io.", "ABCD"));

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(zonesJson, UTF_8)
      .build();
  Object decoded = JacksonIteratorDecoder.create().decode(response,
      new TypeReference<Iterator<Zone>>() {}.getType());
  assertTrue(Iterator.class.isAssignableFrom(decoded.getClass()));
  assertTrue(Closeable.class.isAssignableFrom(decoded.getClass()));
  assertEquals(zones, asList((Iterator<?>) decoded));
}
 
Example #26
Source File: JacksonCodecTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void customDecoder() throws Exception {
  JacksonDecoder decoder = new JacksonDecoder(
      Arrays.asList(
          new SimpleModule().addDeserializer(Zone.class, new ZoneDeserializer())));

  List<Zone> zones = new LinkedList<Zone>();
  zones.add(new Zone("DENOMINATOR.IO."));
  zones.add(new Zone("DENOMINATOR.IO.", "ABCD"));

  Response response = Response.builder()
      .status(200)
      .reason("OK")
      .request(Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
      .headers(Collections.emptyMap())
      .body(zonesJson, UTF_8)
      .build();
  assertEquals(zones, decoder.decode(response, new TypeReference<List<Zone>>() {}.getType()));
}
 
Example #27
Source File: RequestTemplateTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveTemplateWithMixedCollectionFormatsByQuery() {
  RequestTemplate template = new RequestTemplate()
      .method(HttpMethod.GET)
      .collectionFormat(CollectionFormat.EXPLODED)
      .uri("/api/collections")
      .query("keys", "{keys}") // default collection format
      .query("values[]", Collections.singletonList("{values[]}"), CollectionFormat.CSV);

  template = template.resolve(mapOf("keys", Arrays.asList("one", "two"),
      "values[]", Arrays.asList("1", "2")));

  assertThat(template.url())
      .isEqualToIgnoringCase("/api/collections?keys=one&keys=two&values%5B%5D=1%2C2");
}
 
Example #28
Source File: RequestTemplateTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveTemplateWithHeaderWithEscapedCurlyBrace() {
  RequestTemplate template = new RequestTemplate().method(HttpMethod.GET)
      .header("Encoded", "{{{{dont_expand_me}}");

  template.resolve(mapOf("dont_expand_me", "1234"));

  assertThat(template)
      .hasHeaders(entry("Encoded", Collections.singletonList("{{{{dont_expand_me}}")));
}
 
Example #29
Source File: RequestTemplateTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveTemplateWithBinaryBody() {
  RequestTemplate template = new RequestTemplate().method(HttpMethod.GET)
      .uri("{zoneId}")
      .body(new byte[] {7, 3, -3, -7}, null);
  template = template.resolve(mapOf("zoneId", "/hostedzone/Z1PA6795UKMFR9"));

  assertThat(template)
      .hasUrl("/hostedzone/Z1PA6795UKMFR9");
}
 
Example #30
Source File: RequestTemplateTest.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveTemplateWithHeaderSubstitutionsNotAtStart() {
  RequestTemplate template = new RequestTemplate().method(HttpMethod.GET)
      .header("Authorization", "Bearer {token}");

  template = template.resolve(mapOf("token", "1234"));

  assertThat(template)
      .hasHeaders(entry("Authorization", Collections.singletonList("Bearer 1234")));
}