Java 类retrofit.client.Request 实例源码

项目:retrofit1-okhttp3-client    文件:Ok3Client.java   
static okhttp3.Request createRequest(Request request) {
  RequestBody requestBody;
  if (requiresRequestBody(request.getMethod()) && request.getBody() == null) {
    requestBody = RequestBody.create(null, NO_BODY);
  } else {
    requestBody = createRequestBody(request.getBody());
  }

  okhttp3.Request.Builder builder = new okhttp3.Request.Builder()
      .url(request.getUrl())
      .method(request.getMethod(), requestBody);

  List<Header> headers = request.getHeaders();
  for (int i = 0, size = headers.size(); i < size; i++) {
    Header header = headers.get(i);
    String value = header.getValue();
    if (value == null) {
      value = "";
    }
    builder.addHeader(header.getName(), value);
  }

  return builder.build();
}
项目:retrofit1-okhttp3-client    文件:Ok3ClientTest.java   
@Test public void post() throws IOException {
  TypedString body = new TypedString("hi");
  Request request = new Request("POST", HOST + "/foo/bar/", null, body);
  okhttp3.Request okRequest = Ok3Client.createRequest(request);

  assertThat(okRequest.method()).isEqualTo("POST");
  assertThat(okRequest.url().toString()).isEqualTo(HOST + "/foo/bar/");
  assertThat(okRequest.headers().size()).isEqualTo(0);

  RequestBody okBody = okRequest.body();
  assertThat(okBody).isNotNull();

  Buffer buffer = new Buffer();
  okBody.writeTo(buffer);
  assertThat(buffer.readUtf8()).isEqualTo("hi");
}
项目:retrofit1-okhttp3-client    文件:Ok3ClientTest.java   
@Test public void responseNoContentType() throws IOException {
  okhttp3.Response okResponse = new okhttp3.Response.Builder()
      .code(200).message("OK")
      .body(new TestResponseBody("hello", null))
      .addHeader("foo", "bar")
      .addHeader("kit", "kat")
      .protocol(Protocol.HTTP_1_1)
      .request(new okhttp3.Request.Builder()
          .url(HOST + "/foo/bar/")
          .get()
          .build())
      .build();
  Response response = Ok3Client.parseResponse(okResponse);

  assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
  assertThat(response.getStatus()).isEqualTo(200);
  assertThat(response.getReason()).isEqualTo("OK");
  assertThat(response.getHeaders()) //
      .containsExactly(new Header("foo", "bar"), new Header("kit", "kat"));
  TypedInput responseBody = response.getBody();
  assertThat(responseBody.mimeType()).isNull();
  assertThat(buffer(source(responseBody.in())).readUtf8()).isEqualTo("hello");
}
项目:retrofit1-okhttp3-client    文件:Ok3ClientTest.java   
@Test public void emptyResponse() throws IOException {
  okhttp3.Response okResponse = new okhttp3.Response.Builder()
      .code(200)
      .message("OK")
      .body(new TestResponseBody("", null))
      .addHeader("foo", "bar")
      .addHeader("kit", "kat")
      .protocol(Protocol.HTTP_1_1)
      .request(new okhttp3.Request.Builder()
          .url(HOST + "/foo/bar/")
          .get()
          .build())
      .build();
  Response response = Ok3Client.parseResponse(okResponse);

  assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/");
  assertThat(response.getStatus()).isEqualTo(200);
  assertThat(response.getReason()).isEqualTo("OK");
  assertThat(response.getHeaders()) //
      .containsExactly(new Header("foo", "bar"), new Header("kit", "kat"));
  assertThat(response.getBody()).isNull();
}
项目:MVPAndroidBootstrap    文件:ConnectivityAwareUrlClient.java   
@Override
public Response execute(Request request) throws IOException {
    try {
        if (!ConnectivityUtil.isConnected(context)) {
            throw RetrofitError.unexpectedError("Nincs internet", new NoConnectivityException("No Internet"));
        } else {

            Response r = wrappedClient.execute(request);

            checkResult(r);

            return r;
        }
    } catch (RetrofitError retrofitError) {
        if (retry(retrofitError, retries)) {
            return execute(request);
        } else {
            throw new ConnectionError();
        }
    } catch (Exception e) {
        throw new ConnectionError();
    }
}
项目:android-discourse    文件:RequestBuilder.java   
Request build() throws UnsupportedEncodingException {
    String apiUrl = this.apiUrl;

    StringBuilder url = new StringBuilder(apiUrl);
    if (apiUrl.endsWith("/")) {
        // We require relative paths to start with '/'. Prevent a double-slash.
        url.deleteCharAt(url.length() - 1);
    }

    url.append(relativeUrl);

    StringBuilder queryParams = this.queryParams;
    if (queryParams.length() > 0) {
        url.append(queryParams);
    }

    if (multipartBody != null && multipartBody.getPartCount() == 0) {
        throw new IllegalStateException("Multipart requests must contain at least one part.");
    }

    return new Request(requestMethod, url.toString(), headers, body);
}
项目:hochwasser-app    文件:AuthClient.java   
@Override
public Response execute(Request request) throws IOException {
    try {
        List<Header> headers = new LinkedList<Header>(request.getHeaders());

        // if logged in add auth header
        Optional<Account> account = loginManager.getAccount();
        if (account.isPresent()) {
            String token = loginManager.getToken(account.get());
            Header authHeader = new Header("Authorization", "Bearer " + token);
            headers.add(authHeader);
        }

        Request signedRequest = new Request(
                request.getMethod(),
                request.getUrl(),
                headers,
                request.getBody());

        return super.execute(signedRequest);

    } catch (GoogleAuthException gae) {
        throw new IOException(gae);
    }
}
项目:retromock    文件:MockClient.java   
@Override
public Response execute(Request request) throws IOException {
    List<Matcher<? super Request>> unmatchedRoutes = new LinkedList<>();
    for (Route route : routes) {
        if (route.requestMatcher.matches(request)) return route.response.createFrom(request);
        unmatchedRoutes.add(route.requestMatcher);
    }
    StringDescription description = new StringDescription();
    AnyOf.anyOf(unmatchedRoutes).describeTo(description);
    return new Response(
            request.getUrl(),
            404,
            "No route matched",
            Collections.<Header>emptyList(), 
            new TypedString("No matching route found. expected:\n" + description.toString())
    );
}
项目:TruckMuncher-Android    文件:ApiErrorHandlerTest.java   
@Test
public void errorWithEmptyBodyDoesNotCrash() {

    TestClient client = new RestAdapter.Builder()
            .setEndpoint("http://example.com")
            .setClient(new Client() {
                @Override
                public Response execute(Request request) throws IOException {
                    return new Response("", 400, "invalid request", Collections.<Header>emptyList(), null);
                }
            })
            .setErrorHandler(errorHandler)
            .setExecutors(new SynchronousExecutor(), new SynchronousExecutor())
            .build()
            .create(TestClient.class);

    try {
        client.getFullMenus();
        failBecauseExceptionWasNotThrown(ApiException.class);
    } catch (ApiException e) {
        assertThat(e.getMessage()).isNull();
        assertThat(e.getCause()).isNotNull();
    }
}
项目:TruckMuncher-Android    文件:ApiErrorHandlerTest.java   
@Test
public void UnauthorizedOnNonAuthRouteThrowsCorrectException() {
    TestClient client = new RestAdapter.Builder()
            .setEndpoint("http://example.com")
            .setClient(new Client() {
                @Override
                public Response execute(Request request) throws IOException {
                    Error apiError = new Error("1234", "Invalid social credentials");
                    TypedInput input = new TypedByteArray("application/x-protobuf", apiError.toByteArray());
                    return new Response("", 401, "invalid request", Collections.<Header>emptyList(), input);
                }
            })
            .setErrorHandler(errorHandler)
            .setExecutors(new SynchronousExecutor(), new SynchronousExecutor())
            .setConverter(new WireConverter())
            .build()
            .create(TestClient.class);

    try {
        client.getFullMenus();
        failBecauseExceptionWasNotThrown(ExpiredSessionException.class);
    } catch (ExpiredSessionException e) {
        // No-op
    }
}
项目:TruckMuncher-Android    文件:AuthErrorHandlerTest.java   
@Test
public void errorWithEmptyBodyDoesNotCrash() {

    TestClient client = new RestAdapter.Builder()
            .setEndpoint("http://example.com")
            .setClient(new Client() {
                @Override
                public Response execute(Request request) throws IOException {
                    return new Response("", 400, "invalid request", Collections.<Header>emptyList(), null);
                }
            })
            .setErrorHandler(errorHandler)
            .setExecutors(new SynchronousExecutor(), new SynchronousExecutor())
            .build()
            .create(TestClient.class);

    try {
        client.getFullMenus();
        failBecauseExceptionWasNotThrown(ApiException.class);
    } catch (ApiException e) {
        assertThat(e.getMessage()).isNull();
        assertThat(e.getCause()).isNotNull();
    }
}
项目:TruckMuncher-Android    文件:AuthErrorHandlerTest.java   
@Test
public void unauthorizedOnAuthRouteThrowsCorrectException() {
    AuthService service = new RestAdapter.Builder()
            .setEndpoint("http://example.com")
            .setClient(new Client() {
                @Override
                public Response execute(Request request) throws IOException {
                    Error apiError = new Error("1234", "Invalid social credentials");
                    TypedInput input = new TypedByteArray("application/x-protobuf", apiError.toByteArray());
                    return new Response("", 401, "invalid request", Collections.<Header>emptyList(), input);
                }
            })
            .setErrorHandler(errorHandler)
            .setExecutors(new SynchronousExecutor(), new SynchronousExecutor())
            .setConverter(new WireConverter())
            .build()
            .create(AuthService.class);

    try {
        service.getAuth(new AuthRequest());
        failBecauseExceptionWasNotThrown(SocialCredentialsException.class);
    } catch (SocialCredentialsException e) {
        // No-op
    }
}
项目:java-runabove    文件:SigningTest.java   
/**
 * Test signing client.
 */
@Test
public void testSigningClient() {
    LOG.info("Signing Client test");
    // check that the signing process does what it's supposed to do
    SigningClient sc = new SigningClient(new MockClient(), null, null, null, new ExceptionHandler() {

        public Throwable handleError(RetrofitError arg0) {
            return null;
        }

        public void handleException(Exception exception) {
        }
    });

    try {
        Response rs = sc.execute(new Request("GET", "/test", Collections.EMPTY_LIST, new TypedByteArray("application/json", "".getBytes())));
        assertNotNull(rs);
    } catch (IOException e) {
        LOG.error("Signing Client test error", e);
    }

}
项目:java-runabove    文件:SigningTest.java   
/**
 * Test credential client.
 */
@Test
public void testCredentialClient() {
    LOG.info("Credential Client test");
    // check that the signing process does what it's supposed to do
    CredentialClient cc = new CredentialClient(new MockAuthClient(), null, new ExceptionHandler() {

        public Throwable handleError(RetrofitError arg0) {
            return null;
        }

        public void handleException(Exception exception) {
        }
    });
    try {
        Response rs = cc.execute(new Request("GET", "/test", Collections.EMPTY_LIST, new TypedByteArray("application/json", "".getBytes())));
        assertNotNull(rs);
    } catch (IOException e) {
        LOG.error("Signing Client test error", e);
    }
}
项目:http-request-retrofit-client    文件:HttpRequestClient.java   
public static HttpRequest prepareHttpRequest(final Request request) throws IOException {

        // Extract details from incoming request from Retrofit
        final String requestUrl = request.getUrl();
        final String requestMethod = request.getMethod();
        final List<Header> requestHeaders = request.getHeaders();

        // URL and Method
        final HttpRequest httpRequest = new HttpRequest(requestUrl, requestMethod);

        // Headers
        for (Header header: requestHeaders) {
            httpRequest.header(header.getName(), header.getValue());
        }

        return httpRequest;
    }
项目:http-request-retrofit-client    文件:HttpRequestClientIntegrationTest.java   
@Test
public void testPOSTDataEcho() throws Exception {
    // Given
    final String postBodyString = "hello";
    HttpRequestClient httpRequestClient = new HttpRequestClient();
    TypedOutput postBody = new TypedString(postBodyString);
    Request request = new Request("POST", HTTP_BIN_ROOT + "/post", null, postBody);

    // When
    final Response response = httpRequestClient.execute(request);
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> jsonObj = objectMapper.readValue(response.getBody().in(), Map.class);

    // Then
    assertNotNull(response);
    assertThat(response.getStatus(), is(200));
    assertThat(jsonObj.get("data").toString(), is(postBodyString));
}
项目:http-request-retrofit-client    文件:HttpRequestClientIntegrationTest.java   
@Test
public void testSendCustomHeader() throws Exception {
    // Given
    final String X_CUSTOM_AUTH = "X-Custom-Auth";
    final String SOME_AUTH_TOKEN = "SOMEAUTHTOKEN";
    HttpRequestClient httpRequestClient = new HttpRequestClient();
    List<Header> customHeaders = ImmutableList.of(new Header(X_CUSTOM_AUTH, SOME_AUTH_TOKEN));
    Request request = new Request("GET", HTTP_BIN_ROOT + "/get", customHeaders, null);

    // When
    final Response response = httpRequestClient.execute(request);
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> jsonObj = objectMapper.readValue(response.getBody().in(), Map.class);
    Map<String, Object> sentHeaders = (Map<String, Object>) jsonObj.get("headers");

    // Then
    assertNotNull(response);
    assertThat(response.getStatus(), is(200));
    assertThat(sentHeaders.get(X_CUSTOM_AUTH).toString(), is(SOME_AUTH_TOKEN));
}
项目:retrofit-jaxrs    文件:RestAdapter.java   
private static Profiler.RequestInformation getRequestInfo(String serverUrl,
                                                          RestMethodInfo methodDetails, Request request)
{
  long contentLength = 0;
  String contentType = null;

  TypedOutput body = request.getBody();
  if (body != null)
  {
    contentLength = body.length();
    contentType = body.mimeType();
  }

  return new Profiler.RequestInformation(methodDetails.requestMethod, serverUrl,
                                         methodDetails.requestUrl, contentLength, contentType);
}
项目:retrofit-jaxrs    文件:RequestBuilder.java   
Request build() throws UnsupportedEncodingException
{
  String apiUrl = this.apiUrl;

  StringBuilder url = new StringBuilder(apiUrl);
  if (apiUrl.endsWith("/"))
  {
    // We require relative paths to start with '/'. Prevent a double-slash.
    url.deleteCharAt(url.length() - 1);
  }

  url.append(relativeUrl);

  StringBuilder queryParams = this.queryParams;
  if (queryParams.length() > 0)
  {
    url.append(queryParams);
  }

  if (multipartBody != null && multipartBody.getPartCount() == 0)
  {
    throw new IllegalStateException("Multipart requests must contain at least one part.");
  }

  return new Request(requestMethod, url.toString(), headers, body);
}
项目:retrofit-jaxrs    文件:RestAdapterTest.java   
@Test
public void malformedResponseThrowsConversionException() throws Exception
{
  when(mockClient.execute(any(Request.class))) //
      .thenReturn(new Response(200, "OK", NO_HEADERS, new TypedString("{")));

  try
  {
    example.something();
    fail("RetrofitError expected on malformed response body.");
  }
  catch (RetrofitError e)
  {
    assertThat(e.getResponse().getStatus()).isEqualTo(200);
    assertThat(e.getCause()).isInstanceOf(ConversionException.class);
    assertThat(e.getResponse().getBody()).isNull();
  }
}
项目:retrofit-jaxrs    文件:RestAdapterTest.java   
@Test
public void errorResponseThrowsHttpError() throws Exception
{
  when(mockClient.execute(any(Request.class))) //
      .thenReturn(new Response(500, "Internal Server Error", NO_HEADERS, null));

  try
  {
    example.something();
    fail("RetrofitError expected on non-2XX response code.");
  }
  catch (RetrofitError e)
  {
    assertThat(e.getResponse().getStatus()).isEqualTo(500);
  }
}
项目:retrofit-jaxrs    文件:RestAdapterTest.java   
@Test
public void clientExceptionThrowsNetworkError() throws Exception
{
  IOException exception = new IOException("I'm broken!");
  when(mockClient.execute(any(Request.class))).thenThrow(exception);

  try
  {
    example.something();
    fail("RetrofitError expected when client throws exception.");
  }
  catch (RetrofitError e)
  {
    assertThat(e.getCause()).isSameAs(exception);
  }
}
项目:retrofit-jaxrs    文件:RestAdapterTest.java   
@Test
public void closeInputStream() throws IOException
{
  // Set logger and profiler on example to make sure we exercise all the code paths.
  Example example = new RestAdapter.Builder() //
      .setClient(mockClient)
      .setExecutors(mockRequestExecutor, mockCallbackExecutor)
      .setServer("http://example.com")
      .setProfiler(mockProfiler)
      .setLog(RestAdapter.Log.NONE)
      .setLogLevel(FULL)
      .build()
      .create(Example.class);

  ByteArrayInputStream is = spy(new ByteArrayInputStream("hello".getBytes()));
  TypedInput typedInput = mock(TypedInput.class);
  when(typedInput.in()).thenReturn(is);
  Response response = new Response(200, "OK", NO_HEADERS, typedInput);
  when(mockClient.execute(any(Request.class))) //
      .thenReturn(response);
  example.something();
  verify(is).close();
}
项目:retrofit-jaxrs    文件:RestAdapterTest.java   
@Test
public void observableHandlesParams() throws Exception
{
  ArgumentCaptor<Request> requestCaptor = ArgumentCaptor.forClass(Request.class);
  when(mockClient.execute(requestCaptor.capture())) //
      .thenReturn(new Response(200, "OK", NO_HEADERS, new TypedString("hello")));
  ArgumentCaptor<Response> responseCaptor = ArgumentCaptor.forClass(Response.class);
  Action1<Response> action = mock(Action1.class);
  example.observable("X", "Y").subscribe(action);

  Request request = requestCaptor.getValue();
  assertThat(request.getUrl()).contains("/X/Y");

  verify(action).call(responseCaptor.capture());
  Response response = responseCaptor.getValue();
  assertThat(response.getStatus()).isEqualTo(200);
}
项目:retrofit-jaxrs    文件:RequestBuilderTest.java   
@Test
public void getWithPathParamAndInterceptorPathParamAndInterceptorQueryParam() throws Exception
{
  Request request = new Helper() //
      .setMethod("GET") //
      .setUrl("http://example.com") //
      .setPath("/foo/bar/{ping}/{kit}/") //
      .addPathParam("ping", "pong") //
      .addInterceptorPathParam("kit", "kat")
      .addInterceptorQueryParam("butter", "finger")
      .build();
  assertThat(request.getMethod()).isEqualTo("GET");
  assertThat(request.getHeaders()).isEmpty();
  assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/pong/kat/?butter=finger");
  assertThat(request.getBody()).isNull();
}
项目:retrofit-jaxrs    文件:RequestBuilderTest.java   
@Test
public void getWithPathAndQueryParam() throws Exception
{
  Request request = new Helper() //
      .setMethod("GET") //
      .setUrl("http://example.com") //
      .setPath("/foo/bar/{ping}/") //
      .addPathParam("ping", "pong") //
      .addQueryParam("kit", "kat") //
      .addQueryParam("riff", "raff") //
      .build();
  assertThat(request.getMethod()).isEqualTo("GET");
  assertThat(request.getHeaders()).isEmpty();
  assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/pong/?kit=kat&riff=raff");
  assertThat(request.getBody()).isNull();
}
项目:retrofit-jaxrs    文件:RequestBuilderTest.java   
@Test
public void bodyWithPathParams() throws Exception
{
  Request request = new Helper() //
      .setMethod("POST") //
      .setHasBody() //
      .setUrl("http://example.com") //
      .setPath("/foo/bar/{ping}/{kit}/") //
      .addPathParam("ping", "pong") //
      .setBody(Arrays.asList("quick", "brown", "fox")) //
      .addPathParam("kit", "kat") //
      .build();
  assertThat(request.getMethod()).isEqualTo("POST");
  assertThat(request.getHeaders()).isEmpty();
  assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/pong/kat/");
  assertTypedBytes(request.getBody(), "[\"quick\",\"brown\",\"fox\"]");
}
项目:retrofit-jaxrs    文件:RequestBuilderTest.java   
@Test
public void multipartNullRemovesPart() throws Exception
{
  Request request = new Helper() //
      .setMethod("POST") //
      .setHasBody() //
      .setUrl("http://example.com") //
      .setPath("/foo/bar/") //
      .setMultipart() //
      .addPart("ping", "pong") //
      .addPart("fizz", null) //
      .build();
  assertThat(request.getMethod()).isEqualTo("POST");
  assertThat(request.getHeaders()).isEmpty();
  assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/");

  MultipartTypedOutput body = (MultipartTypedOutput) request.getBody();
  List<byte[]> bodyParts = MimeHelper.getParts(body);
  assertThat(bodyParts).hasSize(1);

  Iterator<byte[]> iterator = bodyParts.iterator();

  String one = new String(iterator.next(), "UTF-8");
  assertThat(one).contains("name=\"ping\"").endsWith("\r\npong");
}
项目:retrofit-jaxrs    文件:RequestBuilderTest.java   
@Test
public void simpleHeaders() throws Exception
{
  Request request = new Helper() //
      .setMethod("GET") //
      .setUrl("http://example.com") //
      .setPath("/foo/bar/") //
      .addHeader("ping", "pong") //
      .addHeader("kit", "kat") //
      .build();
  assertThat(request.getMethod()).isEqualTo("GET");
  assertThat(request.getHeaders()) //
      .containsExactly(new Header("ping", "pong"), new Header("kit", "kat"));
  assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/");
  assertThat(request.getBody()).isNull();
}
项目:retrofit-jaxrs    文件:RequestBuilderTest.java   
@Test
public void simpleInterceptorHeaders() throws Exception
{
  Request request = new Helper() //
      .setMethod("GET") //
      .setUrl("http://example.com") //
      .setPath("/foo/bar/") //
      .addInterceptorHeader("ping", "pong") //
      .addInterceptorHeader("kit", "kat") //
      .build();
  assertThat(request.getMethod()).isEqualTo("GET");
  assertThat(request.getHeaders()) //
      .containsExactly(new Header("ping", "pong"), new Header("kit", "kat"));
  assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/");
  assertThat(request.getBody()).isNull();
}
项目:retrofit-jaxrs    文件:RequestBuilderTest.java   
@Test
public void headersAndInterceptorHeaders() throws Exception
{
  Request request = new Helper() //
      .setMethod("GET") //
      .setUrl("http://example.com") //
      .setPath("/foo/bar/") //
      .addHeader("ping", "pong") //
      .addInterceptorHeader("kit", "kat") //
      .build();
  assertThat(request.getMethod()).isEqualTo("GET");
  assertThat(request.getHeaders()) //
      .containsExactly(new Header("ping", "pong"), new Header("kit", "kat"));
  assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/");
  assertThat(request.getBody()).isNull();
}
项目:retrofit-jaxrs    文件:RequestBuilderTest.java   
@Test
public void allThreeHeaderTypes() throws Exception
{
  Request request = new Helper() //
      .setMethod("GET") //
      .setUrl("http://example.com") //
      .setPath("/foo/bar/") //
      .addHeader("ping", "pong") //
      .addInterceptorHeader("kit", "kat") //
      .addHeaderParam("fizz", "buzz") //
      .build();
  assertThat(request.getMethod()).isEqualTo("GET");
  assertThat(request.getHeaders()).containsExactly(new Header("ping", "pong"),
                                                   new Header("kit", "kat"), new Header("fizz", "buzz"));
  assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/");
  assertThat(request.getBody()).isNull();
}
项目:retrofit-jaxrs    文件:RequestBuilderTest.java   
@Test
public void methodHeader() throws Exception
{
  Request request = new Helper() //
      .setMethod("GET") //
      .setUrl("http://example.com") //
      .setPath("/foo/bar/") //
      .addHeader("ping", "pong") //
      .addHeaderParam("kit", "kat") //
      .build();
  assertThat(request.getMethod()).isEqualTo("GET");
  assertThat(request.getHeaders()) //
      .containsExactly(new Header("ping", "pong"), new Header("kit", "kat"));
  assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/");
  assertThat(request.getBody()).isNull();
}
项目:retrofit-jaxrs    文件:RequestBuilderTest.java   
@Test
public void headerParam() throws Exception
{
  Request request = new Helper() //
      .setMethod("GET") //
      .setUrl("http://example.com") //
      .setPath("/foo/bar/") //
      .addHeader("ping", "pong") //
      .addHeaderParam("kit", "kat") //
      .build();
  assertThat(request.getMethod()).isEqualTo("GET");
  assertThat(request.getHeaders()) //
      .containsExactly(new Header("ping", "pong"), new Header("kit", "kat"));
  assertThat(request.getUrl()).isEqualTo("http://example.com/foo/bar/");
  assertThat(request.getBody()).isNull();
}
项目:retrofit-jaxrs    文件:MockRestAdapter.java   
private Request buildRequest(RestMethodInfo methodInfo, RequestInterceptor interceptor,
                             Object[] args) throws Throwable
{
  methodInfo.init();

  // Begin building a normal request.
  RequestBuilder requestBuilder = new RequestBuilder(restAdapter.converter, methodInfo);
  requestBuilder.setApiUrl(restAdapter.server.getUrl());
  requestBuilder.setArguments(args);

  // Run it through the interceptor.
  interceptor.intercept(requestBuilder);

  Request request = requestBuilder.build();

  if (restAdapter.logLevel.log())
  {
    request = restAdapter.logAndReplaceRequest("MOCK", request);
  }

  return request;
}
项目:retrofit-jaxrs    文件:MockRestAdapterTest.java   
@Before
public void setUp() throws IOException
{
  Client client = mock(Client.class);
  doThrow(new AssertionError()).when(client).execute(any(Request.class));

  httpExecutor = spy(new SynchronousExecutor());
  callbackExecutor = spy(new SynchronousExecutor());

  RestAdapter restAdapter = new RestAdapter.Builder() //
      .setClient(client)
      .setExecutors(httpExecutor, callbackExecutor)
      .setServer("http://example.com")
      .setLogLevel(RestAdapter.LogLevel.NONE)
      .build();

  valueChangeListener = mock(ValueChangeListener.class);

  mockRestAdapter = MockRestAdapter.from(restAdapter);
  mockRestAdapter.setValueChangeListener(valueChangeListener);

  // Seed the random with a value so the tests are deterministic.
  mockRestAdapter.random.setSeed(2847);
}
项目:Android_watch_magpie    文件:SecuredRestBuilder.java   
@Override
public void intercept(RequestFacade request) {
    if (!loggedIn) {
        try {
            FormUrlEncodedTypedOutput to = new FormUrlEncodedTypedOutput();
            to.addField("username", username);
            to.addField("password", password);
            to.addField("grant_type", "password");

            String base64Auth = BaseEncoding.base64().encode(new String(clientId + ":" + clientSecret).getBytes());
            List<Header> headers = new ArrayList<Header>();
            headers.add(new Header("Authorization", "Basic " + base64Auth));

            Request req = new Request("POST", tokenIssuingEndpoint, headers, to);

            Response resp = client.execute(req);

            if (resp.getStatus() < 200 || resp.getStatus() > 299) {
                throw new SecuredRestException("Login failure: "
                        + resp.getStatus() + " - " + resp.getReason());
            } else {
                String body = IOUtils.toString(resp.getBody().in());
                accessToken = new Gson().fromJson(body, JsonObject.class).get("access_token").getAsString();
                request.addHeader("Authorization", "Bearer " + accessToken);
                loggedIn = true;
            }
        } catch (Exception e) {
            throw new SecuredRestException(e);
        }
    } else {
        request.addHeader("Authorization", "Bearer " + accessToken);
    }
}
项目:MyTwitterRepo    文件:ConnectivityAwareRetrofitClient.java   
@Override
public Response execute(Request request) throws IOException {
    if (!NetworkHelper.connectedToNetwork(context)) {
        logger.debug("No connectivity %s ", request);
        throw new NoConnectivityException("No connectivity");
    }

    return client.execute(request);
}
项目:retrofit1-okhttp3-client    文件:Ok3ClientTest.java   
@Test public void get() {
  Request request = new Request("GET", HOST + "/foo/bar/?kit=kat", null, null);
  okhttp3.Request okRequest = Ok3Client.createRequest(request);

  assertThat(okRequest.method()).isEqualTo("GET");
  assertThat(okRequest.url().toString()).isEqualTo(HOST + "/foo/bar/?kit=kat");
  assertThat(okRequest.headers().size()).isEqualTo(0);
  assertThat(okRequest.body()).isNull();
}
项目:uphold-sdk-android    文件:MockRestAdapter.java   
public MockRestAdapter(final String responseString, final HashMap<String, String> headers) {
    this.exceptionReference = new AtomicReference<>();
    this.requestReference = new AtomicReference<>();
    this.resultReference = new AtomicReference<>();
    this.mockRestAdapter = new UpholdRestAdapter();
    this.restAdapter = new RestAdapter.Builder().setEndpoint(BuildConfig.API_SERVER_URL)
        .setRequestInterceptor(this.mockRestAdapter.getUpholdRequestInterceptor())
        .setClient(new Client() {
            @Override
            public Response execute(Request request) throws IOException {
                requestReference.set(request);

                return new Response("some/url", 200, "reason", new ArrayList<Header>() {{
                    if (headers != null) {
                        for (Map.Entry<String, String> entry : headers.entrySet()) {
                            String key = entry.getKey();
                            String value = entry.getValue();

                            add(new retrofit.client.Header(key, value));
                        }
                    }
                }}, new TypedByteArray("application/json", responseString == null ? new byte[0] : responseString.getBytes()));
            }
    }).build();

    this.mockRestAdapter.setAdapter(this.restAdapter);
}