public static boolean verify(final Context context, final String username, String password) { boolean verifyResult = false; final ATIPUser user = new ATIPUser(); user.setUserName(username); user.setPwd(password); ATIPRestInterface service = ATIPRestService.getInstance(context); Call<Boolean> call = service.verify(user); call.enqueue( new Callback<Boolean>() { @Override public void onResponse(Call<Boolean> call, Response<Boolean> response) { if (response.body()) { login(context, username); } } @Override public void onFailure(Call<Boolean> call, Throwable t) { Log.v("LoginUtils", t.getMessage()); } }); return verifyResult; }
private void loadMore() { if (nextPageUrl == null || nextPageUrl.isEmpty() || swipeRefreshLayout.isRefreshing()) { return; } swipeRefreshLayout.setRefreshing(true); Call<Reviews> newCall = service.getReviews(String.valueOf(currentPage + 1)); newCall.enqueue( new Callback<Reviews>() { @Override public void onResponse(Response<Reviews> response) { if (!response.isSuccess()) { Toast.makeText(getContext(), "错误码:" + response.code(), Toast.LENGTH_SHORT).show(); return; } Reviews reviews = response.body(); currentPage = reviews.getCurrent_page(); nextPageUrl = reviews.getNext_page_url(); adapter.addAll(reviews.getData()); swipeRefreshLayout.setRefreshing(false); } @Override public void onFailure(Throwable t) { swipeRefreshLayout.setRefreshing(false); } }); }
public void getTeam(final int teamId) { Call<Team> call = mApiService.getTeam(teamId); call.enqueue( new Callback<Team>() { @Override public void onResponse(Call<Team> call, retrofit2.Response<Team> response) { int statusCode = response.code(); Log.d(LOG_TAG, "getTeam statusCode #" + statusCode); if (statusCode != 200) { return; } Team team = response.body(); if (team.getCrestUrl().length() > 0) { GlideHelper.preloadTeamCrest(mContext, mHttpClient, team.getCrestUrl(), team.getId()); File internalFile = mContext.getFileStreamPath("crestTeam" + teamId + ".png"); Uri internal = Uri.fromFile(internalFile); team.setCrestUrl(internal.toString()); } mContext .getContentResolver() .insert(AppProvider.Teams.withId(team.getId()), team.getContentValues()); Log.d(LOG_TAG, "getTeam Complete team ID: " + team.getId()); updateWidgets(mContext); } @Override public void onFailure(Call<Team> call, Throwable t) { // Log error here since request failed // TODO log unable fetch league Log.e(LOG_TAG, "getTeam onFailure", t); } }); }
public void testDirectionAsyncQuery() throws IOException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(MapApiService.API_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); MapApiService.DirectionApi directionApi = retrofit.create(MapApiService.DirectionApi.class); String key = mContext.getString(R.string.google_maps_server_key); String origin = "place_id:ChIJAx7UL8xyhlQR86Iqc-fUncc"; String destination = "place_id:ChIJNbea5OF2hlQRDfHhEXerrAM"; Call<MapApiService.TransitRoutes> call = directionApi.getDirections(origin, destination, key); call.enqueue( new Callback<MapApiService.TransitRoutes>() { @Override public void onResponse( Call<MapApiService.TransitRoutes> call, Response<MapApiService.TransitRoutes> response) { if (response.isSuccess()) { MapApiService.TransitRoutes transitRoutes = response.body(); assertTrue( LOG_TAG + ": retrofit query direction status return: " + transitRoutes.status, transitRoutes.status.equals("OK")); } } @Override public void onFailure(Call<MapApiService.TransitRoutes> call, Throwable t) { Timber.d("Error %s", t.getMessage()); } }); }
/** * POST method with subscriptionId modeled in credentials. Set the credential subscriptionId to * '1234-5678-9012-3456' to succeed. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ public ServiceCall postSwaggerGlobalValidAsync(final ServiceCallback<Void> serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } if (this.client.getSubscriptionId() == null) { serviceCallback.failure( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); return null; } Call<ResponseBody> call = service.postSwaggerGlobalValid( this.client.getSubscriptionId(), this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue( new ServiceResponseCallback<Void>(serviceCallback) { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { serviceCallback.success(postSwaggerGlobalValidDelegate(response)); } catch (ErrorException | IOException exception) { serviceCallback.failure(exception); } } }); return serviceCall; }
@Override protected void load() { swipeRefreshLayout.setRefreshing(true); Call<Reviews> reviewsCall = service.getReviews(null); reviewsCall.enqueue( new Callback<Reviews>() { @Override public void onResponse(Response<Reviews> response) { if (!response.isSuccess()) { Toast.makeText(getContext(), "错误码:" + response.code(), Toast.LENGTH_SHORT).show(); return; } Reviews reviews = response.body(); currentPage = reviews.getCurrent_page(); nextPageUrl = reviews.getNext_page_url(); adapter.reset(reviews.getData()); swipeRefreshLayout.setRefreshing(false); } @Override public void onFailure(Throwable t) { swipeRefreshLayout.setRefreshing(false); } }); }
private void getInfoFromServer() { DescriptionCallBack callBack = new DescriptionCallBack(this, getActivity()); Call<DescriptionData> call = LykkeApplication_.getInstance() .getRestApi() .getDescription( Constants.PART_AUTHORIZATION + userPref.authToken().get(), Constants.USER_AGENT, assetPair.getId()); call.enqueue(callBack); Call<OneAssetPairData> callAssetPair = LykkeApplication_.getInstance() .getRestApi() .getAssetPair(Constants.USER_AGENT, assetPair.getId()); callAssetPair.enqueue( new Callback<OneAssetPairData>() { @Override public void onResponse(Call<OneAssetPairData> call, Response<OneAssetPairData> response) { assetPair = response.body().getResult().getAssetPairs(); initViews(); } @Override public void onFailure(Call<OneAssetPairData> call, Throwable t) {} }); }
/** * Put complex types with array property which is empty. * * @param complexBody Please put an empty array * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ public ServiceCall putEmptyAsync( ArrayWrapper complexBody, final ServiceCallback<Void> serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } if (complexBody == null) { serviceCallback.failure( new IllegalArgumentException("Parameter complexBody is required and cannot be null.")); return null; } Validator.validate(complexBody, serviceCallback); Call<ResponseBody> call = service.putEmpty(complexBody); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue( new ServiceResponseCallback<Void>(serviceCallback) { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { serviceCallback.success(putEmptyDelegate(response)); } catch (ErrorException | IOException exception) { serviceCallback.failure(exception); } } }); return serviceCall; }
@Override public void onPause() { if (pDialog.isShowing()) pDialog.dismiss(); topRatedMovies.cancel(); popularMovies.cancel(); super.onPause(); }
public void getLeague(int leagueId) { Call<SoccerSeason> call = mApiService.getSoccerSeason(leagueId); call.enqueue( new Callback<SoccerSeason>() { @Override public void onResponse( Call<SoccerSeason> call, retrofit2.Response<SoccerSeason> response) { int statusCode = response.code(); Log.d(LOG_TAG, "getLeague statusCode #" + statusCode); if (statusCode != 200) { return; } SoccerSeason season = response.body(); mContext .getContentResolver() .insert(AppProvider.Seasons.withId(season.getId()), season.getContentValues()); Log.d(LOG_TAG, "getLeague Complete league ID: " + season.getId()); updateWidgets(mContext); } @Override public void onFailure(Call<SoccerSeason> call, Throwable t) { // Log error here since request failed // TODO log unable fetch league Log.e(LOG_TAG, "getLeague onFailure", t); } }); }
@Test public void kyc_001_create_one_file() throws IOException { final File tmpFile = File.createTempFile("file1", ".jpg"); final BufferedWriter bw = new BufferedWriter(new FileWriter(tmpFile)); bw.write("This is the temporary file content"); bw.close(); final RequestBody file1 = RequestBody.create(MediaType.parse("image/jpeg"), tmpFile); final Call<KycEntity> call = service.createKYCRequest(TestSettings.testUserAppUserId, file1); final Response<KycEntity> response = call.execute(); if (response.code() != 201) { System.err.println(response.errorBody().string()); } Assert.assertEquals(response.code(), 201); final KycEntity kyc = response.body(); Assert.assertTrue(kyc.Id > 0); Assert.assertTrue(kyc.VoucherCopies.size() > 0); Assert.assertEquals(kyc.Status, KycStatusEnum.IN_PROGRESS); Assert.assertNotNull(kyc.RequestDate); AttachmentEntity attachment = kyc.VoucherCopies.get(0); Assert.assertTrue(attachment.Id > 0); Assert.assertTrue(attachment.Href != null); Assert.assertTrue(attachment.Name != null); Assert.assertTrue(attachment.ContentType.startsWith("image/")); Assert.assertTrue(attachment.Size > 0); }
private void stopHandler() { for (Call<RatesData> call : listRates) { call.cancel(); } isShouldContinue = false; handler.removeCallbacks(run); }
/** * Put complex types with array property which is empty. * * @param complexBody Please put an empty array * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse<Void> putEmpty(ArrayWrapper complexBody) throws ErrorException, IOException, IllegalArgumentException { if (complexBody == null) { throw new IllegalArgumentException("Parameter complexBody is required and cannot be null."); } Validator.validate(complexBody); Call<ResponseBody> call = service.putEmpty(complexBody); return putEmptyDelegate(call.execute()); }
public void fetchFixtures(String timeFrame, String league) { Map<String, String> options = new HashMap<>(); options.put(QUERY_TIME_FRAME, timeFrame); if (league != null) { options.put(QUERY_LEAGUE, league); } Call<FixtureCollection> call = mApiService.getFixtures(options); call.enqueue( new Callback<FixtureCollection>() { @Override public void onResponse( Call<FixtureCollection> call, retrofit2.Response<FixtureCollection> response) { int statusCode = response.code(); Log.d(LOG_TAG, "fetchFixtures statusCode #" + statusCode); if (statusCode != 200) { // TODO set status return; } FixtureCollection fixtureCollection = response.body(); Log.d(LOG_TAG, "Count #" + fixtureCollection.getCount()); Log.d(LOG_TAG, "Time Frame Start " + fixtureCollection.getTimeFrameStart()); Log.d(LOG_TAG, "Time Frame End " + fixtureCollection.getTimeFrameEnd()); Vector<ContentValues> values = new Vector<>(fixtureCollection.getFixtures().size()); for (Fixture fixture : fixtureCollection.getFixtures()) { try { values.add(fixture.getContentValues()); Log.v(LOG_TAG, fixture.getContentValues().toString()); } catch (ParseException e) { e.printStackTrace(); } } int inserted_data; ContentValues[] insert_data = new ContentValues[values.size()]; values.toArray(insert_data); inserted_data = mContext .getContentResolver() .bulkInsert(AppProvider.Fixtures.CONTENT_URI, insert_data); Log.i(LOG_TAG, "fetchMovieItems Complete. " + inserted_data + " Inserted"); // fetch look up data LookupSyncAdapter.syncNow(mContext); updateWidgets(mContext); } @Override public void onFailure(Call<FixtureCollection> call, Throwable t) { // Log error here since request failed Log.e(LOG_TAG, "fetchFixtures onFailure", t); } }); }
/** * POST method with subscriptionId modeled in credentials. Set the credential subscriptionId to * '1234-5678-9012-3456' to succeed. * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse<Void> postSwaggerGlobalValid() throws ErrorException, IOException, IllegalArgumentException { if (this.client.getSubscriptionId() == null) { throw new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null."); } Call<ResponseBody> call = service.postSwaggerGlobalValid( this.client.getSubscriptionId(), this.client.getAcceptLanguage()); return postSwaggerGlobalValidDelegate(call.execute()); }
@Test public void testSearchByLocation() throws IOException { Map<String, String> params = new HashMap<>(); params.put("term", "yelp"); Call<SearchResponse> call = yelpAPI.search("San Francisco", params); Response<SearchResponse> response = call.execute(); Assert.assertEquals(200, response.code()); SearchResponse searchResponse = response.body(); Assert.assertNotNull(searchResponse); }
private void getRates() { if (isShouldContinue) { AssetPairRateCallBack callBack = new AssetPairRateCallBack(this, getActivity()); Call<RateData> call = LykkeApplication_.getInstance() .getRestApi() .getAssetPairsRate( Constants.PART_AUTHORIZATION + userPref.authToken().get(), Constants.USER_AGENT, assetPair.getId()); call.enqueue(callBack); } }
@Test public void testSearchByLocationWithOptionalCoordinate() throws IOException { Map<String, String> params = new HashMap<>(); params.put("term", "yelp"); params.put("cll", "37.7867703362929,-122.399958372115"); Call<SearchResponse> call = yelpAPI.search("San Francisco", params); Response<SearchResponse> response = call.execute(); Assert.assertEquals(200, response.code()); SearchResponse searchResponse = response.body(); Assert.assertNotNull(searchResponse); }
@Test public void anInterface() throws IOException, InterruptedException { server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}")); Call<AnInterface> call = service.anInterface(new AnImplementation("value")); Response<AnInterface> response = call.execute(); AnInterface body = response.body(); assertThat(body.getName()).isEqualTo("value"); RecordedRequest request = server.takeRequest(); assertThat(request.getBody().readUtf8()).isEqualTo("{\"name\":\"value\"}"); assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8"); }
private void login() { NewsTeeApiInterface api = FactoryApi.getInstance(mAppContext); if (session.isLoggedIn()) { HashMap<String, String> userData = db.getUserDetails(); String password = userData.get(SQLiteHandler.KEY_PASSWORD); String email = userData.get(SQLiteHandler.KEY_EMAIL); System.out.println("@@@@@@ Пароль " + password + "@@@@ mail" + email); Call<DataUserAuthentication> userC = null; if (email == null) { String key = userData.get(SQLiteHandler.KEY_SOCIAL_NETWORK_KEY); String snId = userData.get(SQLiteHandler.KEY_SOCIAL_NETWORK_ID); switch (key) { case SQLiteHandler.KEY_GG_ID: userC = api.signIn(snId, null, null, null, "ru"); break; case SQLiteHandler.KEY_FB_ID: userC = api.signIn(null, snId, null, null, "ru"); break; case SQLiteHandler.KEY_VK_ID: userC = api.signIn(null, null, snId, null, "ru"); break; case SQLiteHandler.KEY_TW_ID: userC = api.signIn(null, null, null, snId, "ru"); break; } } else { userC = api.signIn(email, password, "ru"); } if (userC == null) { return; } try { Response<DataUserAuthentication> userR = userC.execute(); String result = userR.body().getResult(); final String msg = userR.body().getMessage(); if (result.equals(Constants.RESULT_SUCCESS)) { User u = userR.body().getData(); ; UserLab.getInstance().setUser(u); new SessionManager(mAppContext).setCountrySettings(u.getLanguage()); } else { db.deleteUsers(); session.setLogin(false); } } catch (IOException e) { e.printStackTrace(); } } }
private void doInscri( String firstNameValue, String lastNameValue, String emailValue, String passwordValue) { hideButton(); progressBar.setVisibility(View.VISIBLE); // github sign in Call<ResponseBody> call = gitHubService.storeUser(firstNameValue, lastNameValue, emailValue, passwordValue); Log.d("user", firstNameValue + " " + lastNameValue + " " + emailValue + " " + passwordValue); call.enqueue( new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { progressBar.setVisibility(View.GONE); JSONObject jsonObject = null; User user = null; try { jsonObject = new JSONObject(response.body().string()); String result = jsonObject.getString("success"); if (result.equals("User exist")) { email.setError("User email exist !"); emailConfirmed.getEditText().setText(""); email.requestFocus(); mdperreur(); } else { JSONObject userJson = jsonObject.getJSONObject("user"); user = new User( userJson.getString("id_User"), userJson.getString("login"), userJson.getString("nom") + " " + userJson.getString("prenom")); AuthUtils.saveUser(InscriptionActivity.this, user); succ(); } } catch (JSONException | IOException | NullPointerException e) { e.printStackTrace(); mdperreur(); } // AuthUtils.saveToken(InscriptionActivity.this, token); AuthUtils.saveUser(InscriptionActivity.this, user); Log.d("success", "last one"); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { progressBar.setVisibility(View.GONE); Toast.makeText(InscriptionActivity.this, "Unable to conenect", Toast.LENGTH_SHORT) .show(); mdperreur(); } }); }
@Test public void anImplementation() throws IOException, InterruptedException { server.enqueue(new MockResponse().setBody("{\"theName\":\"value\"}")); Call<AnImplementation> call = service.anImplementation(new AnImplementation("value")); Response<AnImplementation> response = call.execute(); AnImplementation body = response.body(); assertThat(body.theName).isEqualTo("value"); RecordedRequest request = server.takeRequest(); // TODO figure out how to get Jackson to stop using AnInterface's serializer here. assertThat(request.getBody().readUtf8()).isEqualTo("{\"name\":\"value\"}"); assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8"); }
@AfterViews public void afterViews() { Call<AppInfoData> call = LykkeApplication_.getInstance().getRestApi().getAppInfo(); ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = false; if (activeNetwork == null) { isConnected = false; } else { isConnected = activeNetwork.isConnectedOrConnecting(); } if (isConnected) { call.enqueue( new Callback<AppInfoData>() { @Override public void onResponse(Call<AppInfoData> call, Response<AppInfoData> response) { AppInfoResult.setInstance(response.body().getResult()); new Handler() .postDelayed( new Runnable() { @Override public void run() { if (userPref.authToken().get().isEmpty()) { Intent intent = new Intent(); intent.setClass(getApplicationContext(), SignInActivity_.class); startActivity(intent); finish(); } else { Intent intent = new Intent(); intent.setClass(getApplicationContext(), RestoreActivity_.class); finish(); startActivity(intent); } } }, Constants.DELAY_500); } @Override public void onFailure(Call<AppInfoData> call, Throwable t) {} }); } else { Intent intent = new Intent(); intent.setClass(getApplicationContext(), SignInActivity_.class); startActivity(intent); finish(); } }
@Test public void testSearchByCoordinateOptions() throws IOException { CoordinateOptions coordinate = CoordinateOptions.builder().latitude(37.7867703362929).longitude(-122.399958372115).build(); Map<String, String> params = new HashMap<>(); params.put("term", "yelp"); Call<SearchResponse> call = yelpAPI.search(coordinate, params); Response<SearchResponse> response = call.execute(); Assert.assertEquals(200, response.code()); SearchResponse searchResponse = response.body(); Assert.assertNotNull(searchResponse); }
public void testDirectionQuery() throws IOException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(MapApiService.API_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); MapApiService.DirectionApi directionApi = retrofit.create(MapApiService.DirectionApi.class); String key = mContext.getString(R.string.google_maps_server_key); String origin = "place_id:ChIJAx7UL8xyhlQR86Iqc-fUncc"; String destination = "place_id:ChIJNbea5OF2hlQRDfHhEXerrAM"; Call<MapApiService.TransitRoutes> call = directionApi.getDirections(origin, destination, key); MapApiService.TransitRoutes transitRoutes = call.execute().body(); assertTrue( LOG_TAG + ": retrofit query direction status return: " + transitRoutes.status, transitRoutes.status.equals("OK")); }
public void onPokemonClicked(int pokeNum) { final Call<Pokemon> pokeCall = pokeApiService.getPokemon(pokeNum); pokeCall.enqueue( new Callback<Pokemon>() { @Override public void onResponse(Call<Pokemon> call, Response<Pokemon> response) { final Pokemon pokemon = response.body(); mListener.onPokemonSelected(pokemon); } @Override public void onFailure(Call<Pokemon> call, Throwable t) { t.getCause(); } }); }
public void onLogin(View view) throws InterruptedException { rotateLoading.start(); String login = email.getText().toString().isEmpty() ? " " : email.getText().toString(); String password = pass.getText().toString().isEmpty() ? " " : pass.getText().toString(); Call<LoginResponse> call = API.login(login, password); call.enqueue( new Callback<LoginResponse>() { @Override public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) { Log.d("loginresponse", String.valueOf(response.body())); LoginResponse loginresponse = response.body(); if (loginresponse.success()) { Log.d("loginresponse.getId()", String.valueOf(loginresponse.getId())); SharedPreferences.Editor editor = mSettings.edit(); editor.putBoolean(APP_PREFERENCES_AUTH, true); editor.putInt(APP_PREFERENCES_UID, loginresponse.getId()); editor.apply(); Intent intent = new Intent(MainActivity.this, LanguagesActivity.class); startActivity(intent); } else { rotateLoading.stop(); Toast toast = Toast.makeText( getApplicationContext(), "Неправильный логин или пароль", Toast.LENGTH_LONG); toast.show(); } } @Override public void onFailure(Call<LoginResponse> call, Throwable t) { Log.d("onFailureLogin", "onFailureLogin"); rotateLoading.stop(); Toast toast = Toast.makeText( getApplicationContext(), "Неправильный логин или пароль", Toast.LENGTH_LONG); toast.show(); } }); }
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent == null) { Log.d(this, "Oh noes, intent is null"); } mAllWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); mContext = this; Log.d(this, "About to call radar"); MetClient client = ServiceGenerator.createService(MetClient.class); Call<Radar> call = client.getRadar(); call.enqueue(this); return super.onStartCommand(intent, flags, startId); }
/** * Gets the current usage count and the limit for the resources under the subscription. * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the UsageListResultInner object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse<UsageListResultInner> list() throws CloudException, IOException, IllegalArgumentException { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException( "Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException( "Parameter this.client.apiVersion() is required and cannot be null."); } Call<ResponseBody> call = service.list( this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); return listDelegate(call.execute()); }
@Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (savedInstanceState == null && mQueryResult == null) { RequestBody shopId = RequestBody.create(MediaType.parse("multipart/form-data"), String.valueOf(getShopId())); File imageFile = new File(mImageFileName); File scaledImageDir = new File(imageFile.getParentFile(), "downsized"); File f = new File(scaledImageDir, imageFile.getName()); // File f = new File(mImageFileName); RequestBody file = RequestBody.create(MediaType.parse("multipart/form-data"), f); String str = FileUtils.readTextFile(new File(mImageMetaFileName)); str = "{\"image\": {\"meta\": " + str + "}}"; RequestBody json = RequestBody.create(MediaType.parse("multipart/form-data"), str); Call<ImageQueryResult> call = RestClient.getSharedInstance().getApiService().getAnnotationsOnImage(file, shopId, json); mProgressDialog = new ProgressDialog(getActivity(), R.style.AppTheme_Dark_Dialog); mProgressDialog.setIndeterminate(true); mProgressDialog.setMessage("Searching..."); mProgressDialog.show(); call.enqueue( new Callback<ImageQueryResult>() { @Override public void onResponse( Call<ImageQueryResult> call, Response<ImageQueryResult> response) { mProgressDialog.hide(); mQueryResult = response.body(); mAnnotationList.clear(); mAnnotationList.addAll(mQueryResult.annotations); mAnnotationAdaptor.notifyDataSetChanged(); mLinearLayoutManager.scrollToPosition(3); drawAnnotations(); } @Override public void onFailure(Call<ImageQueryResult> call, Throwable t) { mProgressDialog.hide(); Toast.makeText(getActivity(), "Failed to fetch annotations.", Toast.LENGTH_LONG) .show(); } }); } }