Tuesday, July 21, 2015

Include HttpHeaders to Google Cloud API call request made from Android

When making Cloud Endpoint API call request from the Android client sometimes it's needed to add Http Headers to that request. This blog post say how to add Date http header to request that calls myApi.sayHi() method which is described here. Read the code of EndpointsAsyncTask class. The code where http headers must be set is shown below.



MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
                    new AndroidJsonFactory(), null)
                // options for running against local devappserver
                // - 10.0.2.2 is localhost's IP address in Android emulator
                // - turn off compression when running against local devappserver
                .setRootUrl("http://10.0.2.2:8080/_ah/api/")
                .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                    @Override
                    public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                        abstractGoogleClientRequest.setDisableGZipContent(true);
                    }
                });
                // end options for devappserver

            myApiService = builder.build();



Now add the Date http header as below. The bold text are the code that is used to add http header to request.



                MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
                        new AndroidJsonFactory(), null)
                        // options for running against local devappserver
                        // - 10.0.2.2 is localhost's IP address in Android emulator
                        // - turn off compression when running against local devappserver
                        .setRootUrl("http://10.0.2.2:8080/_ah/api/")
                        .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                            @Override
                            public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                                abstractGoogleClientRequest.setDisableGZipContent(true);


                                Calendar calendar = Calendar.getInstance();
                                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");

                                HttpHeaders headers = abstractGoogleClientRequest.getRequestHeaders();                                Log.d(TAG, "Date: "+dateFormat.format(calendar.getTime()));
                                headers.setDate(dateFormat.format(calendar.getTime()));
                                abstractGoogleClientRequest.setRequestHeaders(headers);
                            }
                        });

                myApiService = builder.build();

No comments:

Post a Comment