retrofit.client.Response Java Examples

The following examples show how to use retrofit.client.Response. 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: WearService.java    From TutosAndroidFrance with MIT License 7 votes vote down vote up
@Override
public void hello() {
    //Utilise Retrofit pour réaliser un appel REST
    AndroidService androidService = new RestAdapter.Builder()
            .setEndpoint(AndroidService.ENDPOINT)
            .build().create(AndroidService.class);

    //Récupère et deserialise le contenu de mon fichier JSON en objet List<AndroidVersion>
    androidService.getElements(new Callback<List<AndroidVersion>>() {
        @Override
        public void success(List<AndroidVersion> androidVersions, Response response) {

            //envoie cette liste à la montre
            wearProtocol.onAndroidVersionsReceived(androidVersions);
        }

        @Override
        public void failure(RetrofitError error) {
        }
    });
}
 
Example #2
Source File: ProfilePhotoFragment.java    From Expert-Android-Programming with MIT License 6 votes vote down vote up
private void getUserReviews() {

        RetroInterface.getZomatoRestApi().getUserPhotos(
                user_id,
                new Callback<RestaurantImageResponse>() {
                    @Override
                    public void success(RestaurantImageResponse restaurantImageResponse, Response response) {

                        if(restaurantImageResponse!=null)
                        {
                            restaurantImages = restaurantImageResponse.getItems();
                            profileRestaurantImageAdapter.refresh(restaurantImages);
                        }

                    }

                    @Override
                    public void failure(RetrofitError error) {

                    }
                }
        );


    }
 
Example #3
Source File: ApiFactory.java    From droidddle with Apache License 2.0 6 votes vote down vote up
public static String getErrorMessage(Response response) {
    String text = responseToString(response);
    try {
        JSONObject object = new JSONObject(text);
        if (object.has("errors")) {
            JSONArray errors = object.getJSONArray("errors");
            if (errors.length() > 0) {
                JSONObject error = errors.getJSONObject(0);
                if (error.has("message")) {
                    return error.getString("message");
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
        Log.e("Api", "getErrorMessage: "+text );
    }
    if (response.getStatus() > 500) {
        return App.getContext().getString(R.string.check_network);
    }
    return null;
}
 
Example #4
Source File: RxJavaLeakFragment.java    From AndroidAll with Apache License 2.0 6 votes vote down vote up
public void doRetrofit() {
    if (otherApi == null) {
        otherApi = ApiServiceFactory.createService(OtherApi.class);
    }
    retrofitSubscription = otherApi.testTimeout("10000")
            .onTerminateDetach()
            .subscribe(new Action1<Response>() {
                @Override
                public void call(Response response) {
                    String content = new String(((TypedByteArray) response.getBody()).getBytes());
                    Log.d("RxJavaLeakFragment", RxJavaLeakFragment.this + ":" + content);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    throwable.printStackTrace();
                }
            });
}
 
Example #5
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 6 votes vote down vote up
@Test
public void shouldFollowAPlaylist() throws Exception {
    final Type modelType = new TypeToken<Result>() {}.getType();
    final String body = ""; // Returns empty body
    final Result fixture = mGson.fromJson(body, modelType);

    final Response response = TestUtils.getResponseFromModel(fixture, modelType);

    final String owner = "thelinmichael";
    final String playlistId = "4JPlPnLULieb2WPFKlLiRq";

    when(mMockClient.execute(argThat(new ArgumentMatcher<Request>() {
        @Override
        public boolean matches(Object argument) {
            final Request request = (Request) argument;
            return request.getUrl().endsWith(String.format("/users/%s/playlists/%s/followers",
                    owner, playlistId)) &&
                    "PUT".equals(request.getMethod());
        }
    }))).thenReturn(response);

    final Result result = mSpotifyService.followPlaylist(owner, playlistId);
    this.compareJSONWithoutNulls(body, result);
}
 
Example #6
Source File: TryWhenFragment.java    From AndroidAll with Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(View v) {
    super.onClick(v);
    switch (v.getId()) {
        case R.id.btn_operator:
            tvLogs.setText("");
            userApi.getUserInfoNoToken()
                    .retryWhen(new RetryWithDelay(3, 3000))
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new Action1<Response>() {
                        @Override
                        public void call(Response response) {
                            String content = new String(((TypedByteArray) response.getBody()).getBytes());
                            printLog(tvLogs, "", content);
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            throwable.printStackTrace();
                        }
                    });
    }
}
 
Example #7
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 6 votes vote down vote up
@Test
public void shouldCheckFollowingUsers() throws IOException {
    Type modelType = new TypeToken<List<Boolean>>() {
    }.getType();
    String body = TestUtils.readTestData("follow_is_following_users.json");
    List<Boolean> fixture = mGson.fromJson(body, modelType);

    final String userIds = "thelinmichael,wizzler";

    Response response = TestUtils.getResponseFromModel(fixture, modelType);

    when(mMockClient.execute(argThat(new ArgumentMatcher<Request>() {
        @Override
        public boolean matches(Object argument) {
            try {
                return ((Request) argument).getUrl().contains("type=user") &&
                        ((Request) argument).getUrl().contains("ids=" + URLEncoder.encode(userIds, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                return false;
            }
        }
    }))).thenReturn(response);

    Boolean[] result = mSpotifyService.isFollowingUsers(userIds);
    this.compareJSONWithoutNulls(body, result);
}
 
Example #8
Source File: GsonResponse.java    From divide with Apache License 2.0 6 votes vote down vote up
public Response build(){
    return new Response(url,status,reason,new ArrayList<Header>(),new TypedInput() {
        @Override
        public String mimeType() {
            return null;
        }

        @Override
        public long length() {
            return length;
        }

        @Override
        public InputStream in() throws IOException {
            return is;
        }
    });
}
 
Example #9
Source File: ShareRest.java    From NightWatch with GNU General Public License v3.0 6 votes vote down vote up
private boolean loginAndGetData() {
    dexcomShareAuthorizeInterface().getSessionId(new ShareAuthenticationBody(password, login), new Callback() {
        @Override
        public void success(Object o, Response response) {
            Log.d("ShareRest", "Success!! got a response on auth.");
            String returnedSessionId = new String(((TypedByteArray) response.getBody()).getBytes()).replace("\"", "");

            getBg(returnedSessionId);
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            Log.e("RETROFIT ERROR: ", ""+retrofitError.toString());
        }
    });
    return true;
}
 
Example #10
Source File: ManagementApiUtilTest.java    From apiman-cli with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeAndCheckResponse_RetrofitError() throws Exception {
    // test data
    response = new Response(URL, HttpURLConnection.HTTP_NOT_FOUND, "Not Found",
            newArrayList(), new TypedString(""));

    // mock behaviour
    when(request.get()).thenThrow(RetrofitError.httpError(URL, response, null, null));

    // test
    try {
        ManagementApiUtil.invokeAndCheckResponse(HttpURLConnection.HTTP_OK, request);
        fail(CommandException.class + " expected");

    } catch (CommandException ignored) {
        // verify behaviour
        verify(request).get();
    }
}
 
Example #11
Source File: BitCoinService.java    From android-open-project-demo with Apache License 2.0 6 votes vote down vote up
@Subscribe
public void onRequsetGetInfo(GetInfoEvent event) {

    mBitCoinInterface.contributors(new Callback<Ticker>() {
        @Override
        public void success(Ticker ticker, Response response) {
            mLastTicker = ticker;
            // success
            mBus.post(new GetInfoDoneEvent(true, null, ticker));
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            mBus.post(new GetInfoDoneEvent(false, retrofitError, null));
        }
    });
}
 
Example #12
Source File: SetHandleActivity.java    From Expert-Android-Programming with MIT License 6 votes vote down vote up
private void updateHandle(String handle) {

        RetroInterface.getZomatoRestApi().setUserHandle(
                SessionPreference.getUserId(context) + "",
                handle,
                new Callback<NormalResponse>() {
                    @Override
                    public void success(NormalResponse normalResponse, Response response) {
                        if (normalResponse.isSuccess()) {
                           // Toas.show(context, "Handle set Successfully");
                            showError("Handle set Successfully", true);
                            finish();
                        } else {
                           // Toas.show(context, "Handle already in use");
                            showError("Handle already in use", false);
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {

                    }
                }
        );
    }
 
Example #13
Source File: Ok3ClientTest.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #14
Source File: ApiClientUnitTest.java    From braintree_android with MIT License 6 votes vote down vote up
@Test(timeout = 10000)
public void createTransaction_createsAUnionPayTransaction() throws InterruptedException {
    mApiClient.createTransaction("fake-valid-unionpay-credit-nonce", "fake_switch_usd",
            new Callback<Transaction>() {
                @Override
                public void success(Transaction transaction, Response response) {
                    assertTrue(transaction.getMessage().contains("created") && transaction.getMessage().contains("authorized"));
                    mCountDownLatch.countDown();
                }

                @Override
                public void failure(RetrofitError error) {
                    fail(error.getMessage());
                }
            });

    mCountDownLatch.await();
}
 
Example #15
Source File: Ok3ClientTest.java    From retrofit1-okhttp3-client with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #16
Source File: SnippetDetailFragment.java    From Android-REST-API-Explorer with MIT License 6 votes vote down vote up
private int getColor(Response response) {
    int color;
    switch (response.getStatus() / 100) {
        case 1:
        case 2:
            color = R.color.code_1xx;
            break;
        case 3:
            color = R.color.code_3xx;
            break;
        case 4:
        case 5:
            color = R.color.code_4xx;
            break;
        default:
            color = R.color.transparent;
    }
    return color;
}
 
Example #17
Source File: ApiClientUnitTest.java    From braintree_android with MIT License 6 votes vote down vote up
@Test(timeout = 10000)
public void getClientToken_returnsAClientToken() throws InterruptedException {
    mApiClient.getClientToken(null, null, new Callback<ClientToken>() {
        @Override
        public void success(ClientToken clientToken, Response response) {
            assertNotNull(clientToken.getClientToken());
            mCountDownLatch.countDown();
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            fail(retrofitError.getMessage());
        }
    });

    mCountDownLatch.await();
}
 
Example #18
Source File: PostsScreen.java    From Mortar-Flow-Dagger2-demo with MIT License 6 votes vote down vote up
private void load() {

            restClient.getService().getPosts(new Callback<List<Post>>() {
                @Override
                public void success(List<Post> loadedPosts, Response response) {
                    if (!hasView()) return;
                    Timber.d("Success loaded %s", loadedPosts.size());

                    posts.clear();
                    posts.addAll(loadedPosts);
                    adapter.notifyDataSetChanged();

                    getView().show();
                }

                @Override
                public void failure(RetrofitError error) {
                    if (!hasView()) return;
                    Timber.d("Failure %s", error.getMessage());
                }
            });
        }
 
Example #19
Source File: ApiClientUnitTest.java    From braintree-android-drop-in with MIT License 6 votes vote down vote up
@Test(timeout = 30000)
public void createTransaction_createsAUnionPayTransaction() throws InterruptedException {
    mApiClient.createTransaction("fake-valid-unionpay-credit-nonce", "fake_switch_usd",
            new Callback<Transaction>() {
                @Override
                public void success(Transaction transaction, Response response) {
                    assertTrue(transaction.getMessage().contains("created") && transaction.getMessage().contains("authorized"));
                    mCountDownLatch.countDown();
                }

                @Override
                public void failure(RetrofitError error) {
                    fail(error.getMessage());
                }
            });

    mCountDownLatch.await();
}
 
Example #20
Source File: ManagementApiUtilTest.java    From apiman-cli with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeAndCheckResponse_StatusMatch() throws Exception {
    // test data
    response = new Response(URL, HttpURLConnection.HTTP_OK, "OK",
            newArrayList(), new TypedString("test body"));

    // mock behaviour
    when(request.get()).thenReturn(response);

    // test
    ManagementApiUtil.invokeAndCheckResponse(request);

    // assertions
    verify(request).get();
}
 
Example #21
Source File: UserFragment.java    From droidddle with Apache License 2.0 5 votes vote down vote up
private void updateFollowingStatus(Response response) {
    stopMenuLoading();
    if (response.getStatus() == 204) {
        mIsFollowing = true;
    } else if (response.getStatus() == 404) {
        mIsFollowing = false;
    }

    mFollowMenu.setChecked(mIsFollowing);
    mFollowMenu.setTitle(mIsFollowing ? R.string.action_unfollow : R.string.action_follow);
}
 
Example #22
Source File: WearService.java    From TutosAndroidFrance with MIT License 5 votes vote down vote up
/**
 * Appellé à la réception d'un message envoyé depuis la montre
 *
 * @param messageEvent message reçu
 */
@Override
public void onMessageReceived(MessageEvent messageEvent) {
    super.onMessageReceived(messageEvent);

    //Ouvre une connexion vers la montre
    ConnectionResult connectionResult = mApiClient.blockingConnect(30, TimeUnit.SECONDS);

    if (!connectionResult.isSuccess()) {
        Log.e(TAG, "Failed to connect to GoogleApiClient.");
        return;
    }

    //traite le message reçu
    final String path = messageEvent.getPath();

    if (path.equals("bonjour")) {

        //Utilise Retrofit pour réaliser un appel REST
        AndroidService androidService = new RestAdapter.Builder()
                .setEndpoint(AndroidService.ENDPOINT)
                .build().create(AndroidService.class);

        //Récupère et deserialise le contenu de mon fichier JSON en objet Element
        androidService.getElements(new Callback<List<Element>>() {
            @Override
            public void success(List<Element> elements, Response response) {
                envoyerListElements(elements);
            }

            @Override
            public void failure(RetrofitError error) {
            }
        });

    }
}
 
Example #23
Source File: MoverAuthenticator.java    From Mover with Apache License 2.0 5 votes vote down vote up
private String findUserImage(Response response){
    try {
        if (isResponseSuccess(response)) {
            return Jsoup.parse(asString(response))
                    .select("#channel-box .userpic img").attr("src");
        }
    }catch (RetrofitError er){
        return  null;
    }

    return null;
}
 
Example #24
Source File: ShotFragment.java    From droidddle with Apache License 2.0 5 votes vote down vote up
private void uploadAttachment() {
    if (!Utils.hasInternet(getActivity())) {
        Toast.makeText(getActivity(), R.string.check_network, Toast.LENGTH_SHORT).show();
        return;
    }
    Context mContext = getActivity();
    mDialog = UiUtils.showProgressDialog(mContext, getString(R.string.creating_attachment));
    TypedFile file = new TypedFile(FileUtils.getMimeType(mFile), mFile);
    Observable<Response> observable = ApiFactory.getService(mContext).createShotAttachments(mShot.id, file);
    observable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new SucessCallback<Response>(mContext, R.string.create_attachment_success, mDialog), new ErrorCallback(mContext, mDialog));
}
 
Example #25
Source File: LoginActivity.java    From android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onValidationSucceeded() {
    LoadingDialogFragment.show(getSupportFragmentManager());
    VPNService.get(mUsername.getText().toString(), mPassword.getText().toString()).servers(new Callback<ServersResponse>() {
        @Override
        public void success(ServersResponse serversResponse, Response response) {
            LoadingDialogFragment.dismiss(getSupportFragmentManager());
            PrefUtils.save(LoginActivity.this, Preferences.USERNAME, mUsername.getText().toString());
            PrefUtils.save(LoginActivity.this, Preferences.PASSWORD, mPassword.getText().toString());

            mDoNotSave = true;
            if (getIntent().getBooleanExtra(PROCEED_TO_MAIN, true)) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            } else {
                setResult(RESULT_OK);
                finish();
            }
        }

        @Override
        public void failure(RetrofitError error) {
            LoadingDialogFragment.dismiss(getSupportFragmentManager());
            if (error != null && error.getResponse() != null && error.getResponse().getStatus() == 401) {
                Toast.makeText(LoginActivity.this, R.string.credentials_incorrect, Toast.LENGTH_SHORT).show();
            }
        }
    });
}
 
Example #26
Source File: MockAuthWebService.java    From divide with Apache License 2.0 5 votes vote down vote up
@Override
public Response login(@Body LoginCredentials credentials) {
    try{
        Credentials dbCreds = authServerLogic.userSignIn(credentials);
        return new GsonResponse("",200,"",null, dbCreds).build();
    }catch(DAO.DAOException e) {
        return new GsonResponse("",e.getStatusCode(),e.getMessage(), null, null).build();
    }
}
 
Example #27
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetArtistRelatedArtists() throws Exception {
    String body = TestUtils.readTestData("artist-related-artists.json");
    Artists fixture = mGson.fromJson(body, Artists.class);

    Response response = TestUtils.getResponseFromModel(fixture, Artists.class);
    when(mMockClient.execute(isA(Request.class))).thenReturn(response);

    Artists tracks = mSpotifyService.getRelatedArtists("test");
    compareJSONWithoutNulls(body, tracks);
}
 
Example #28
Source File: ApiServiceTest.java    From android-test-demo with MIT License 5 votes vote down vote up
public void testEventsRequest() {
    getApiService().getEvents("google", new Callback<Events>() {
        @Override
        public void success(Events events, Response response) {
            assertNotNull(events);
            assertFalse(events.isEmpty());
        }

        @Override
        public void failure(RetrofitError error) {

        }
    });
}
 
Example #29
Source File: UserFragment.java    From droidddle with Apache License 2.0 5 votes vote down vote up
private void checkFollowingRes(Response res) {
    stopMenuLoading();
    if (res.getStatus() == 204) {
        swapFollowStatus();
    }
    TypedInput body = res.getBody();
}
 
Example #30
Source File: SpotifyServiceTest.java    From spotify-web-api-android with MIT License 5 votes vote down vote up
@Test
public void shouldGetPlaylistTracks() throws IOException {
    Type modelType = new TypeToken<Pager<PlaylistTrack>>() {
    }.getType();

    String body = TestUtils.readTestData("playlist-tracks.json");
    Pager<PlaylistTrack> fixture = mGson.fromJson(body, modelType);

    Response response = TestUtils.getResponseFromModel(fixture, modelType);
    when(mMockClient.execute(isA(Request.class))).thenReturn(response);

    Pager<PlaylistTrack> playlistTracks = mSpotifyService.getPlaylistTracks("test", "test");
    compareJSONWithoutNulls(body, playlistTracks);
}