28
Фев
2020

Как правильно реализовать обработку запроса к серверу методом POST?

Смысл в чем: Имеется клиент серверное приложение, в связке клиент/сервер/мастер

Необходимо, реализовать запрос sendCoordinates в ServerApi.java

и реализовать аналогичный метод в ActivitySplesh.java Можете подсказать/показать, как это можно сделать?

Необходимо, чтобы приложение обрабатывало запрос в ServerApi с координатами

ServerApi.java

@POST("orders/method/setCurrentLocation")
Call<okhttp3.ResponseBody> sendCoordinates(
            @Header("X-App-Version") String version,
            @Header("X-Static-Version") String staticVer,
            @Header("X-Token") String xtoken,
            @Query("user_current_latitude") Double latitude,
            @Query("user_current_longitude") Double longitude);

AcitivitySplesh.java

@EActivity(R.layout.v5_activity_splesh)
public class ActivitySplesh extends GGActivity
{
    private static final String TAG = GGApplication.TAG + "ASplash";

    private boolean landingStage = false;
    private boolean orderStage  = true;
//    private int orderAttemptCount = 0;
//    private int userAttemptCount = 0;
    private int checkBaseServerUrlAttemptCount = 0;
    private boolean checkGoogleStage = true;
    private boolean checkLocation = false;
    private boolean loadStatic = true;
    private boolean noNetwork = true;
    private boolean checkBaseServer = false;
    // dog-nail for resume of splash screen
    private boolean nextStage = false;
    private Long requestedChatOrderId = null;

    @ViewById
    protected TextViewPlus tv_problem;

    @ViewById (R.id.splesh_progress)
    protected ImageView imageProgress;

    @ViewById (R.id.image_star)
    protected ImageView imageStar;

    @ViewById (R.id.tv_version)
    protected TextView tvVersion;

    protected Dialog diaGps = null;
    private Location location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        landingStage = false;
        autoSwitcher = false;
        bannerBlock = true;

        EventBus.getDefault().register(this);
        Router.instance();
        startGeoLocation();
        startService(ServiceWebSocket.launcher(this));

        Bundle extras = getIntent().getExtras();
        if (extras != null){

            for (String key : extras.keySet()) {
                Object value = extras.get(key);
                if (value != null) {
                    Log.d(TAG, String.format("%s %s (%s)", key,
                            value.toString(), value.getClass().getName()));
                }
            }

            String method = extras.getString("method","").toLowerCase();
            if (TextUtils.equals(method,"openorder")) {

                String sOrderId = extras.getString("order_id", "");

                long orderId = -1L;
                try {
                    orderId = Long.parseLong(sOrderId);
                } catch (Exception ignored) {

                }

                if (orderId != -1) {
                    new OrderState().setOrderId(orderId).activate();
                    eventReqCurrentOrder.post();

                    Log.e(TAG, "PUSH openOrder  " + orderId);
                }

            } else if (TextUtils.equals(method,"openchat")){
                String sChatOrderId = extras.getString("order_id", "");

                long chatOrderId = -1;
                try {
                    chatOrderId = Long.parseLong(sChatOrderId);
                } catch (Exception ignored) {

                }

                requestedChatOrderId = chatOrderId != -1 ? chatOrderId : null;

                Log.e(TAG, "PUSH openChat  " + chatOrderId);
            }
        }
    }


    private void startGeoLocation() {

        if (ServiceManager.isGpsEnabled(this)){
            if (ServiceLocation.instance() != null)
                ServiceLocation.instance().getFast();
            else
                startService(ServiceLocation.launcher(this));

            checkLocation = Router.instance().getModel().hasLastSelfLocation();


        }

    }

    @Override
    public void onStart() {
        super.onStart();
        GGApplication.instance().mainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                reconnect();
            }
        },0);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Subscribe
    public void onEvent(eventUpdatedLocation event) {
        if (Router.instance().getModel().hasLastSelfLocation()||
                Settings.ignoreLocationRequirement){
            if (!checkLocation) {
                checkLocation = true;
                checkAllTaskComplite();
            }
        }
    }

    @Subscribe
    public void onEvent(eventClientChange event) {
//        Log.e(GGApplication.TAG,"Autoswitcher");
//        GGApplication.activitySwitcher(this);
    }

    @Subscribe(sticky = true)
    public void onEvent(eventStaticUpdate event){
        EventBus.getDefault().removeStickyEvent(event);
        if (GGStatic.instance().getState() == GGStatic.State.ERROR){
            loadStatic = false;
//            GGStatic.instance().download();
        } else if (GGStatic.instance().getState() == GGStatic.State.READY) {
            staticStepReady();
        }
    }

    private void staticStepReady() {
        loadStatic = true;
        getCurUser();
        sendCoordinates();
        checkAllTaskComplite();
    }

    @AfterViews
    protected void afterViews() {
        Log.w(TAG,"after view:");
        showVersion();

        cmdFirebaseTokenSend
                .create()
                .exec();
    }

    private void checkBaseServer() {
        if (GGApplication.baseServerApi() != null){
            GGApplication.baseServerApi().listRegions(
                    GGApplication.getVersionHeader(),
                    "",
                    Settings.getLanguage(),
                    null,
                    null)
                    .enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    JSONObject result = RestUtils.getJSONWithErrorControl(response);

                    if (result != null){
                        Log.i(GGApplication.TAG, "listRegions: " + result);
                    }

                    if (RestUtils.isOK(result)) {
                        JSONObject data = RestUtils.getData(result);
                        ServerNamesKeeper.instance().initRegionList(data);
                        if (ServerNamesKeeper.instance().correctCurrentServerByCurrentRegion()){
                            ServerNamesKeeper.instance().save(ActivitySplesh.this);
                        }

                        checkBaseServer  = true;

                        getDataFromServer();

                    } else {
                        recheckBaseServer();
                    }

                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    recheckBaseServer();
                    Log.e(GGApplication.TAG, "listRegions: FAILURE : " + t.getMessage());
                }
            });
        } else {
            recheckBaseServer();
        }
    }

    public void reconnect(){
        Log.e(TAG, "reconnect: ");

        boolean skipWelcome = Router.instance().getModel().user.welcomeDone;
        if (skipWelcome) {
            //TODO сделать обработку реконнекта
            tv_problem.setVisibility(View.INVISIBLE);

            if (!Settings.ignoreGoogleServices) {

                int gserviceState = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
                if (gserviceState != ConnectionResult.SUCCESS) {
                    if (GooglePlayServicesUtil.isUserRecoverableError(gserviceState)) {
                        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(gserviceState, this, 0);
                        if (dialog != null)
                            dialog.show();
                    } else {
                        Toast.makeText(this, getResources().getString(R.string.technical_check_loading_error_gs_not_supported),
                                Toast.LENGTH_LONG).show();
                    }
                    checkGoogleStage = false;
                } else {
                    checkGoogleStage = true;
                }
            } else {
                checkGoogleStage = true;
            }

            nextStage = false;
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(0);
            } else {

                nextStep();
            }
        } else {
            startActivity(ActivityWelcome.launcher(this));
            LocUtils.animForward(this);
            finish();
        }
    }

    private void nextStep() {
        checkBaseServerUrlAttemptCount = 0;
        nextStage = true;
        noNetwork = false;
        checkBaseServer = false;
        checkLocation = !Settings.ignoreLocationRequirement || Router.instance().getModel().hasLastSelfLocation();

        if (!ServiceManager.isNetworkAvailable(this)) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    GGApplication.showToast(R.string.alert_connection_lost_message);
                }
            }, 500);

            tv_problem.setText(getResources().getString(R.string.alert_connection_lost_message));
            noNetwork = true;
        } else if (!ServiceManager.isGpsEnabled(this) && !ServiceManager.gpsSkip) {

            Log.w(TAG, "No GPS try show dialog");

            if (diaGps == null) {
                diaGps = DialogTextWithOkCancel.show(this, R.string.alert_master_location_disabled,
                        R.string.common_turnon,
                        new DialogTextWithOkCancel.OnCompleteClick() {
                            @Override
                            public void action() {
                                startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                                diaGps = null;
                            }
                        },
                        R.string.common_cancel,
                        new DialogTextWithOkCancel.OnCompleteClick() {
                            @Override
                            public void action() {
                                diaGps = null;
                            if (BuildConfig.IS_MASTER) {
                                // exit
                                Intent intent = new Intent(Intent.ACTION_MAIN);
                                intent.addCategory(Intent.CATEGORY_HOME);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                ActivitySplesh.this.startActivity(intent);
                            } else {
                                ServiceManager.gpsSkip = true;
                                nextStep();
                            }
                            }
                        });
            }

            return;
        } else {
            checkBaseServer();

            GGApplication.instance.mainHandler.postDelayed(
                    new Runnable() {
                        @Override
                        public void run() {
                            landingStage = true;
                            checkAllTaskComplite();
                        }
                    }
                    , 1000);
        }

        GGApplication.instance.mainHandler.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        if (GGApplication.getCurrent() == ActivitySplesh.this) {
                            showProblem();
                        }
                    }
                },
                60*1000);
    }


    public void recheckBaseServer() {
        if (GGApplication.instance().tryNextBaseServer()){
            checkBaseServerUrlAttemptCount++;
        }

        if (checkBaseServerUrlAttemptCount < 3){
            checkBaseServer();
        } else {
            checkBaseServer = false;
            DialogTextWithOk.show(this, R.string.alert_connection_lost_message, new DialogTextWithOkCancel.OnCompleteClick() {
                @Override
                public void action() {

                }
            });
            checkAllTaskComplite();
        }
    }

    private void getDataFromServer() {
        if (GGApplication.apiS() != null) {
            staticStepRun();
//            getCurUser();
        } else {
            orderStage = true;
            loadStatic = true;
            checkAllTaskComplite();
        }
    }


    private static class PermissionRecord {
        private String  mPermission;
        private int     mRequestMsgId;
        private int     mGrantMsgId;
        private boolean mIsGranted;

        public PermissionRecord(String permission, int requestMsgId, int grantMsgId) {
            mPermission     = permission;
            mRequestMsgId   = requestMsgId;
            mGrantMsgId     = grantMsgId;
            mIsGranted      = false;
        }

        public String getPermission() {
            return mPermission;
        }

        public int getRequestMsgId() {
            return mRequestMsgId;
        }

        public int getGrantMsgId() {
            return mGrantMsgId;
        }

        public boolean isPermissionGranted() {
            return mIsGranted;
        }

        public void grantPermission() {
            mIsGranted = true;
        }
    }

    private static final int REQUEST_CAMERA         = 0x01;
    private static final int REQUEST_INTERNET       = 0x02;
    private static final int REQUEST_LOCATION       = 0x03;
    private static final int REQUEST_PHONE          = 0x04;
    private static final int WRITE_EXTERNALSTORAGE  = 0x05;

    private static final SparseArray<PermissionRecord> mPermissionState = new SparseArray<PermissionRecord>() {
        {
            append( REQUEST_CAMERA,
                    new PermissionRecord(
                            Manifest.permission.CAMERA,
                            R.string.permission_camera_rationale,
                            R.string.permission_camera_granted
                    )
            );
            append( REQUEST_INTERNET,
                    new PermissionRecord(
                            Manifest.permission.INTERNET,
                            R.string.permission_internet_rationale,
                            R.string.permission_internet_granted
                    )
            );
            append( REQUEST_LOCATION,
                    new PermissionRecord(
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            R.string.permission_location_rationale,
                            R.string.permission_location_granted
                    )
            );
            append( REQUEST_PHONE,
                    new PermissionRecord(
                            Manifest.permission.CALL_PHONE,
                            R.string.permission_phone_rationale,
                            R.string.permission_phone_granted
                    )
            );
            append( WRITE_EXTERNALSTORAGE,
                    new PermissionRecord(
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            R.string.permission_writeexternalstorage_rationale,
                            R.string.permission_writeexternalstorage_granted
                    )
            );
        }
    };

    /**
     * Callback received when a permissions request has been completed.
     */

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, int[] grantResults) {
...
    }

    private void requestPermissions(int permissionIndex) {

        View layout = findViewById(R.id.listview);

//        Log.d(TAG,"cycle count: " + permissionIndex);

        if (permissionIndex < mPermissionState.size()) {
            final PermissionRecord permissionInfo = mPermissionState.valueAt(permissionIndex);
            final int permissionTag = mPermissionState.keyAt(permissionIndex);

//            Log.d(TAG, "Requesting permission: " + permissionInfo.getPermission());
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, permissionInfo.getPermission())) {
                final String[] permissionArray = new String[]{permissionInfo.getPermission()};
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissionInfo.getPermission())) {
                    final Activity act = this;
                    Snackbar.make(
                            layout,
                            permissionInfo.getRequestMsgId(),
                            Snackbar.LENGTH_INDEFINITE
                    ).setAction(R.string.common_OK, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ActivityCompat.requestPermissions(
                                    act,
                                    permissionArray,
                                    permissionTag
                            );
                        }
                    }).show();
                } else {
                    ActivityCompat.requestPermissions(
                            this,
                            permissionArray,
                            permissionTag
                    );
                }
            } else {
                permissionInfo.grantPermission();
                requestPermissions(permissionIndex + 1);
            }
        } else {
            startGeoLocation();
            nextStep();
        }
    }

    public void getCurUser(){
        ...
    }

    private void staticStepRun() {
        if (GGStatic.instance().getState() == GGStatic.State.READY) {
            staticStepReady();
        } else {
            loadStatic = false;
            GGStatic.instance().download();
        }
    }

    /*
        This method needs to be configured.
     */

    public void sendCoordinates() {
        GGApplication.apiS().sendCoordinates(
                GGApplication.getVersionHeader(),
                GGStatic.instance().getVersion(),
                GGApplication.getTokenHeader(),
                latitude,
                longitude)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        JSONObject result = RestUtils.getJSONWithErrorControl(response);


                        if (result != null) {
                            Log.w(TAG, "user_coordinates " + result);
                        }

                        if (RestUtils.isOK(result)) {

                            final LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                            Router.instance().getModel().setLastSelfLocation(latLng);
                            final EventBus eventBus = EventBus.getDefault();
                            if (eventBus.hasSubscriberForEvent(eventUpdatedLocation.class)) {
                                eventBus.post(new eventUpdatedLocation(latLng));

                                if (Settings.logLocationService)
                                    Log.d(TAG, "Updated location send to event bus");
                            }
                            int userId = Router.instance().getModel().user.getId();


                            EventBus.getDefault().postSticky(new         eventOutSendLocation(userId, latLng));

                            if (Settings.logLocationService)
                                Log.d(TAG, "Updated location for userId = " + userId +
                                        " lat: " + latLng.latitude + ", lng: " + latLng.longitude);

                            checkAllTaskComplite();
                        } else {
                            GGApplication.showToast(RestUtils.getErrorMessage(result));

                        }
                    }
                    @Override
                    public void onFailure(Call<okhttp3.ResponseBody> call, Throwable t) {
                        GGApplication.serverTempHandler();
                        Log.e(TAG, "orderList: FAILURE : " + t.getMessage());
                    }
                });
    }

    public void getCurrentOrder() {
        ...
    }

    public void checkAllTaskComplite(){
        if (orderStage && landingStage && checkGoogleStage &&
                checkLocation && checkBaseServer) {

            if (requestedChatOrderId != null){

                Order order  = ClientModel.instance().orderQueue().findOrder(requestedChatOrderId);
                Order root  = ClientModel.instance().orderQueue().findMainOrder(requestedChatOrderId);
                if (order != null &&
                        root != null){


                    OrderState
                            .create()
                            .setOrder(root)
                            .post(ChatState
                                    .create()
                                    .setOrder(order))
                            .activate();
                } else {
                    // chat from history
                    ChatState chat = ChatState
                            .create()
                            .history(true)
                            .setOrderId(requestedChatOrderId);

                    OrderHistoryState details = OrderHistoryState
                            .create()
                            .orderId(requestedChatOrderId)
                            .post(chat);

                    OrderHistoryListState
                            .create()
                            .post(details)
                            .activate();

                }

                requestedChatOrderId = null;
            }

            GGApplication.instance.mainHandler.post(
                    new Runnable() {
                        @Override
                        public void run() {
                            Router.instance().onEvent(new eventOrderQueueChanged());

                            Intent i = ActivityController.instance().getRelevantIntent(ActivitySplesh.this);
                            if (i != null && !switching) {
                                switching = true;
                                startActivity(i);
                                finish();
                                LocUtils.animForward(ActivitySplesh.this);
//                                overridePendingTransition(R.anim.slide_left_in, com.glossyglobe.R.anim.slide_left_out);
                                finish();
                            } else {
                                //TODO inform NO relevant activity
                                Log.e(GGApplication.TAG, "No activity");
                            }
                        }
                    });


        } else {
            Log.i(GGApplication.TAG,
                    "Try failed : order-" + orderStage +
                    "baseServer - " + checkBaseServer +
                    " googleServices-" + checkGoogleStage +
                    " location-" + checkLocation +
                    " static-" + loadStatic +
                    " landing" + landingStage);
        }
    }

    public void showProblem(){
        ...
      }

    public static Intent launcher(Context context) {
        return new Intent(context, ActivitySplesh_.class);
    }

    public static Intent launcherInit(Context context) {
        Intent intent = new Intent(context, ActivitySplesh_.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        return intent;
    }

}

}

Источник: https://ru.stackoverflow.com/questions/1088794/%D0%9A%D0%B0%D0%BA-%D0%BF%D1%80%D0%B0%D0%B2%D0%B8%D0%BB%D1%8C%D0%BD%D0%BE-%D1%80%D0%B5%D0%B0%D0%BB%D0%B8%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C-%D0%BE%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%BA%D1%83-%D0%B7%D0%B0%D0%BF%D1%80%D0%BE%D1%81%D0%B0-%D0%BA-%D1%81%D0%B5%D1%80%D0%B2%D0%B5%D1%80%D1%83-%D0%BC%D0%B5%D1%82%D0%BE%D0%B4%D0%BE%D0%BC-post
Share

Тебе может это понравится...