Customed HTTP requests with Cloud Endpoints - android

I have an API working with Cloud Endpoints and I added its generated client library to my Android app.
However I don't know how to add information to my requests. For now, here is the only HTTP request I know how to send using the client library:
DrinkEndpoint.Builder builder = new DrinkEndpoint.Builder(AndroidHttp.newCompatibleTransport(),new GsonFactory(), null);
DrinkEndpoint service = builder.build();
Drink drink = new Drink();
drink.setName(params[0]);
response = service.insertDrink(drink).execute();
So my question is: how to modify this request to add information either in the headers or in the body of the request?
For instance, I want to add a String that is not an attribute of the Drink entity.
Thank you

Your insertDrink(drink) method returns a InsertDrink instance which is a child of InsertDrinkEndpointRequest.
The InsertDrinkEndpointRequest instance allows you to set the request header by calling the setRequestHeaders(httpHeader) method.
In your case: service.insertDrink(drink).setRequestHeaders(httpHeader).execute().
This way of building a cloud endpoint request may help you: https://stackoverflow.com/a/21492950/2205582

Related

How to implement custom AWSCredentialsProvider?

I need to replace CognitoCachingCredentialsProvider with custom AWSCredentialsProvider, to add custom headers with every IoT request, is this possible and how?
My current code snippet:
CognitoCachingCredentialsProvider credentialsProvider;
AWSIotDataClient iotDataClient = new AWSIotDataClient(credentialsProvider); iotDataClient.setEndpoint(AWSConstants.CUSTOMER_SPECIFIC_ENDPOINT);
GetThingShadowRequest request = new GetThingShadowRequest()
.withThingName(AWSConstants.TEMP_THING_NAME);
GetThingShadowResult result = iotDataClient.getThingShadow(request);
Now what I want to do is to replace CognitoCachingCredentialsProvider with custom CredentialsProvider to add custom headers with every iot request.
My Team just contacted aws support and the above question is not applicable.
Edit: aws team is working on that right now, feature will be available soon

Twilio Status callback url

I am working on voice calling app which is built in java and I need to know the call status when it is picked , rejected or complated.My server end is in java.
I set status callback url while placing a call as mention in the twilio docs. My question which url is to added in that code and do i need to add the funtion for that end point url also.
And what should be the code in that funtion like what are the parameters as I need to print the call status
com.twilio.type.Client clientEndpoint = new com.twilio.type.Client("client:" + to);
PhoneNumber from = new PhoneNumber(CALLER_ID);
// Make the call
Call call = Call.creator(clientEndpoint, from, uri).setMethod(HttpMethod.POST)
.setStatusCallbackMethod(HttpMethod.POST)
.setStatusCallback(URI.create("https://57fb8b2c.ngrok.io/events"))
.setStatusCallbackEvent(
Arrays.asList(Call.Event.ANSWERED.toString(), Call.Event.COMPLETED.toString(),
Call.Event.INITIATED.toString(), Call.Event.RINGING.toString()))
.create(client);
// Print the call SID (a 32 digit hex like CA123..)
System.out.println(call.getSid() + "//" + call.getStatus());
return call.getSid();
Twilio developer evangelist here.
I'm not particularly good at Java, but I can help with what happens when you set a statusCallback URL.
For each of the events you set as the statusCallbackEvent you will receive an HTTP request to your statusCallback URL when the call enters that state.
You will need to implement an endpoint (in your case, at the path /events as that's the URL you are setting) that can receive these incoming HTTP requests.
When Twilio makes the status callback request it includes all the regular webhook parameters, such as CallSid so you can tie the request to the known call sid.
The request will also include some other parameters, most importantly in your case the CallStatus parameter. The value will be one of queued, initiated, ringing, in-progress, busy, failed, or no-answer. There's more on what they mean here.
I hope that helps a bit.

How to cancel ongoing request in retrofit when retrofit.client.UrlConnectionClient is used as client?

I am using retrofit for http calls in my Android application and retrofit.client.UrlConnectionClient as the client while building the adapter.
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(url)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(
new Client.Provider() {
public Client get() {
return new UrlConnectionClient() {
#Override
protected HttpURLConnection openConnection(Request request)
throws IOException {
HttpURLConnection connection = super.openConnection(request);
connection.setConnectTimeout(connectionTimeout);
return connection;
}
I wanted to set the timeout so I have used UrlConnectionClient as my client. I could not find a way with other clients like OkHttp.
Question is : How can I cancel the ongoing request ?.
I have seen a similar post # Using Square's Retrofit Client, is it possible to cancel an in progress request? If so how? but my code would get really complex if I try to add my own executors and try to cancel the request using that. I am looking if there is slightly a better way with my existing code.
I also see that Retorofit V2.0 has plan for Retry and Cancel but not sure when that would be released..https://github.com/square/retrofit/issues/297
Need help !
In fact I also need a way to retry with the same code.
This has been available since 2.0.0-beta2 (https://github.com/square/retrofit/releases/tag/parent-2.0.0-beta2). I don't know if there is a doc that explains that but here is the link to API:
http://square.github.io/retrofit/2.x/retrofit/retrofit/Call.html#cancel--
'Call' API allows to do Retry as well by 'Clone'ing the request.

Android Retrofit session - cookies

I am using retrofit to deserialize json request from web server and I need to create a session (cookie?) in my app (which should expire in 120 min). The problem is I don't know how to implement it.
private RestAdapter adapter = RestAdapter.Builder().setClient(????).setServer("http://192.168.0.1").build();
This session should persist only if the application is running.
Min SDK requirement is 8
Ok,you know the retrofit actually uses the okhttp inside the framework.
And you should know the "Interceptor"
When you init a okhttp in retrofit, you should invoke addInterceptor, just like this:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.retryOnConnectionFailure(true);
builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
builder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
builder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
builder.addInterceptor(new ZCommonIntercepter());
Custom your own Intercepter extends Intercepter.
And get the sessionId by response.header("Set-cookie") save it as a Constant or something in your memory.
Every request after this you should remove the original header("cookie")
and addHeader (the thing that you have already saved)
I'm sorry that i'm not a native english speaker. If you can not understand me. I will just give you some keywords, you can google it.
---Key words---
interceptor in okhttp
cookies in request header or response header

Checking google android subscriptions from server side

in a nutshell:
Can I work with the Google Play Android Developer API from server-side without providing any app in the play store?
Background:
I'm working on a project which provides apps with monthly subscriptions. The coresponding data of each subscription (purchase token, date etc) gets stored in the backend database.
Now I want to create a cronjob that iterates through each of these datasets.And for each subscription I'd like to contact the Google API to retrieve the information if the subscription is still valid or not, and update our database corresponding to the responsed status.
For the backend logic I use the google-api-java-client library.
To either cancel or verify subscriptions I need to authenticate myself with OAuth2 before.
Been there, done that.
new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes("https://www.googleapis.com/auth/androidpublisher") // $1
.setServiceAccountPrivateKeyFromP12File(new File(filePath))
.setClientSecrets(CLIENT_ID, CLIENT_SECRET) // $2
.build();
$1: I don't know if the given account scope is valid. Because I just could find this value in a very few examples, but neither in this overview nor in the google playground
$2 I guess this is necessary, even though I found a lot of example which did not provide this information.
But, unfortunately, I can't see any differences when I provide invalid data (like wrong email or private key).
Questions
How can i verify that the GoogleCredential is correct?
May I just see it in the next steps, like contacting ie the androidpublisher API?
In the next step I try to get purchase status of a subscription:
Androidpublisher publisher = new Androidpublisher.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(GOOGLE_PRODUCT_NAME) // $1
.build();
Androidpublisher.Purchases purchases = publisher.purchases();
Androidpublisher.Purchases.Get get = purchases.get("android.test.purchased", "monthly001", "mytoken"); // $2
SubscriptionPurchase subscripcion = get.execute();
$1: My dummy product name from the API console -> API Access
$2: Beside the fact, that the androidpush API does not allow contacting it via service accounts, but only via web server applications auth flow, I don't have any clue what to insert in the parameter of the get- method.
Here's the API:
https://developers.google.com/android-publisher/v1/purchases/get
Questions
What is the package name and what is the subscriptionId in this context?
Where do I get/set these values?
After reading this document I know there is a way to to deal with fake/static responses. But I can't read anywhere if this is also possible for subscriptions, or just for in-app-billings on mobile devices only.
I'm wondering anyway why/if there is any easy way of developing with a sandbox or s.th. simliar.
I still have the feeling that I'm just missing a big part to understand how the things should work.
Maybe someone of you can give me a hint how to proceed at this place or may say me where i'm wrong.
Kind regards,
Christopher
I could now figure out most of my previous understanding problems.
=1= GENERATE AUTHORIZATION URL
String authorizeUrl = new GoogleAuthorizationCodeRequestUrl(googleClientId,callbackUrl,"https://www.googleapis.com/auth/androidpublisher").build()
// See why: http://stackoverflow.com/questions/8433990/when-authenticating-with-oauth-and-youtube-always-get-error-invalid-grant-on
authorizeUrl += "&approval_prompt=force&access_type=offline"
=2= AUTHENTICATE
Since the server-webflow is not working for the androidpublisher API the customer must now call the URL generated in (1) manually.
=3= CALLBACK
The google callback should process the next steps. The callback contains the parameter "code" which we have to use.
=4= REQUEST AUTH-TOKEN
// Build the HTTP parameter
Map<String,String> params = [:]
params.put("grant_type", "authorization_code")
params.put("code", code.encodeAsURL())
params.put("client_id", customer.googleClientId.encodeAsURL())
params.put("client_secret", customer.googleClientSecret.encodeAsURL())
params.put("redirect_uri", getCallbackUrl().encodeAsURL())
// Send the POST request
// This action might throw an exception in case any parameter were wrong, invalid or not specified.
String result = HttpRequestHandler.sendRequest("https://accounts.google.com/o/oauth2/token", params);
JSONElement jsonResult = JSON.parse(result)
// Map result
OAuth2Result oAuth2Result = new OAuth2Result()
oAuth2Result.accessToken = jsonResult.getAt("access_token")
oAuth2Result.refreshToken = jsonResult.getAt("refresh_token")
oAuth2Result.ttlSeconds = Integer.parseInt(jsonResult.getAt("expires_in").toString())
oAuth2Result.tokenType = jsonResult.getAt("token_type")
=5= REQUEST REFRESH TOKEN
// Build the HTTP parameter
Map<String,String> params = [:]
params.put("grant_type", "refresh_token")
params.put("refresh_token", this.customer.googleRefreshToken.encodeAsURL())
params.put("client_id", customer.googleClientId.encodeAsURL())
params.put("client_secret", customer.googleClientSecret.encodeAsURL())
// Send the POST request
// This action might throw an exception in case any parameter were wrong, invalid or not specified.
String result = HttpRequestHandler.sendRequest("https://accounts.google.com/o/oauth2/token", params);
JSONElement jsonResult = JSON.parse(result)
// Map result
OAuth2Result oAuth2Result = new OAuth2Result()
oAuth2Result.accessToken = jsonResult.getAt("access_token")
oAuth2Result.refreshToken = jsonResult.getAt("refresh_token")
oAuth2Result.ttlSeconds = Integer.parseInt(jsonResult.getAt("expires_in").toString())
oAuth2Result.tokenType = jsonResult.getAt("token_type")

Categories

Resources