I set up a connection between Android and AWS Lambda which has the endpoint set to SageMaker. I am using the REST API during the connection, the AWS Cognito plug is set to be accessed without authorization.
I make a connection as described here:
https://aws.amazon.com/blogs/machine-learning/call-an-amazon-sagemaker-model-endpoint-using-amazon-api-gateway-and-aws-lambda/
My question is how to send this data:
{"data":"13.49,22.3,86.91,561.0,0.08752,0.07697999999999999,0.047510000000000004,0.033839999999999995,0.1809,0.057179999999999995,0.2338,1.3530000000000002,1.735,20.2,0.004455,0.013819999999999999,0.02095,0.01184,0.01641,0.001956,15.15,31.82,99.0,698.8,0.1162,0.1711,0.2282,0.1282,0.2871,0.06917000000000001"}
And how to view the received response later. Anyone know how to do it or where I can find tips on how to do it?
If I understand correctly, this is your system flow:
POST some data from your Android device
It gets received by API Gateway
And continues through to AWS Lambda
In AWS Lambda the data is extracted, and passed to Sage Maker
Creating a POST using AWS Amplify
To POST data form the Android device, follow the Amplify API (REST) category documentation.
Specifically, you can do something like:
val options = RestOptions.builder()
.addPath("/prod/predictbreastcancer")
.addBody("{\"data\":\"13.49,22.3,86.91,561.0,0.08752,0.07697999999999999,0.047510000000000004,0.033839999999999995,0.1809,0.057179999999999995,0.2338,1.3530000000000002,1.735,20.2,0.004455,0.013819999999999999,0.02095,0.01184,0.01641,0.001956,15.15,31.82,99.0,698.8,0.1162,0.1711,0.2282,0.1282,0.2871,0.06917000000000001\"}".toByteArray())
.build()
Amplify.API.post(options,
{ Log.i("Demo", "POST response = $it") },
{ Log.e("Demo", "POST failed", it) }
)
Creating POST body from EditText content
You mentioned you're using an EditText widget to gather the input data. I assume a user can enter a comma-separated list of values like 0.44, 6.11, etc.
To extract it's content and build the POST body, you can do:
val input = findViewById(R.id.input) as EditText
val body = JSONObject()
.put("data", input.text)
.toString()
.replaceAll("\"", "\\\"")
Displaying response in another Activity
Skimming the blog you referenced, I can't see an example of the response body content. But, here's how you can retrieve response JSON and pass it to a new activity.
Amplify.API.post(options,
{ response ->
val intent = Intent(this, YourOtherActivity::class.java)
intent.putExtra("json", response.data.asString())
runOnUiThread { startActivity(intent) }
},
{ /* handle error ... */ }
)
In YourOtherActivity, access the extra data in onCreate() like so:
val json = intent.getStringExtra("json")
Related
I want to get all the uploaded photos of the logged in user that was uploaded today. I could fetch all the photos and filter it with the created_time field. But I would like to make the request to Facebook api to just send me todays photos.
This is the code I am using to get users uploaded photos
fun getAllPhotos() {
val bundle =Bundle()
bundle.putString(
"fields",
"album,alt_text,created_time,event,place,alt_text_custom,name,name_tags,target,source"
)
tempPhotos.clear()
val request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/me/photos/uploaded",
object : GraphRequest.Callback {
override fun onCompleted(response: GraphResponse) {
val type = object : TypeToken<ApiResponseObject>() {}.type
val respJSON = response.getJSONObject()
val item: ApiResponseObject = Gson().fromJson(respJSON.toString(), type)
item.data.forEach {
if (UtilityFunctions.checkIfToday(it.createdTime)) {
tempPhotos.add(it)
} else {
return#forEach
}
}
}
})
request.parameters = bundle
request.executeAsync()
}
As you can see I request for all photos to "/me/photos/uploaded/" I would like to only request for photos on a certain date ( or just today )
I saw that the response came sorted by created time so I returned from the loop whenever I saw some picture that was out of date.
Hey can you provide some more information regarding the issue you are facing with your code.
eg. some examples of how facebook api response structure is, some code snippets etc.
Edited response:
I crawled a while for the internet to search for your problem as it is difficult to create custom query in graph api and I have never used it before. What you are doing in your code is not bad either but if you insist on creating a custom query to api then I have found a github repository that might help you
Facebook Graph API query builder
I found the solution. I just needed to look into the pagination documentation
I found that just as fields I could also send since and a unix timestamp and it would return the photos uploaded since that timestamp
I'm new to GraphQL using the Apollo client on Android. I'm trying to sign up a user on the server via graphQL mutation.
I call a mutation and if user's data is not valid I get http code 422: Unprocessible Entity, and in this case I cannot get any response details. I use standard way to make a call:
.enqueue(object : ApolloCall.Callback<CreateUserMutation.Data>() {
override fun onFailure(e: ApolloException) {
}
override fun onResponse(response:
Response<CreateUserMutation.Data>) {
}
And after this I'm in the onFailure block. ApolloException contains only http code description. But I want to see error details in a full response, that I can see via the Postman. I've already tried com.apollographql.apollo.ApolloCall.Callback#onHttpError callback, but the networkResponse body = null. I've described this problem here, but haven't fixed my problem:
https://github.com/apollographql/apollo-android/issues/1166
The way to do this is to check if ApolloException is an instanceof ApolloHttpException.
If it is, you can get the throwable.rawResponse().code() from it.
If it's not it means it isn't server error (maybe timeout or others)
I am currently working on creating a custom authentication for a Xamarin.Android app using Azure. I have successfully created my API and it is properly returning values when submitting a raw payload using Advanced REST Client.
I am now trying to implement this on Xamarin.Android using Azure's MobileServiceClient SDK and when using the invokeApi method as demonstrated below in my code, I am getting an exception indicating that it is calling GET instead of POST. Is anyone aware of what I might be doing wrong?
ex.Message returns
"Cannot GET /api/register?username=azureAccountTest&password=testingpassword"
public async Task RegisterAsync()
{
Dictionary<string, string> user = new Dictionary<string, string>
{
{ "username", username },
{ "password", password }
};
try
{
CancellationToken ct;
var result = await client.InvokeApiAsync("register", HttpMethod.Post, user, ct);
}
catch(Exception ex)
{
var message = ex.Message;
}
}
According to your description, I tested this issue on my local side and I could retrieve the authenticationToken as follows:
You used the following method for InvokeApiAsync:
public Task<JToken> InvokeApiAsync(string apiName, HttpMethod method, IDictionary<string, string> parameters, CancellationToken cancellationToken = default(CancellationToken));
Note: It summarizes that the Additional data will sent to through the query string.
Per my understanding, you could refer to the following method for sending additional data though the HTTP content as follows:
JObject user = new JObject();
user.Add("username", "bruce");
user.Add("password", "123456");
var result = await App.MobileService.InvokeApiAsync("/.auth/login/custom", HttpMethod.Post, user, ct);
Additionally, you need to specific the mobileAppUri with https endpoint when deploy to azure side. Here is a similar issue, you could refer to here. Moreover, I would recommend you refer to adrian hall's book about Custom Authentication.
UPDATE:
Based on your comment, I checked the custom authentication and found the following note from adrian hall's book about Custom Authentication:
You must turn on Authentication / Authorization in your App Service. Set the Action to take when request is not authenticated to Allow Request (no action) and do not configure any of the supported authentication providers.
I am having a problem getting a parameter sent from android app into go application. I called r.FormValue(key) but it returned null. I want to find the way to check what are parameters available on Go side after the android app sent the post data to it. Is there any way to do this, getting all parameters without using keys?
The Request structure in go has a Form field which is populated with request parameters after ParseForm() is called.
Form contains the parsed form data, including both the URL field's
query parameters and the POST or PUT form data.This field is only
available after ParseForm is called. The HTTP client ignores Form and
uses Body instead.
You could try adding the following code after receiving a request:
func(w http.ResponseWriter, request *http.Request) {
request.ParseForm()
log.Printf("%v",request.Form)
//....
}
If this is for debugging, you can use DumpRequest:
func(w http.ResponseWriter, r *http.Request) {
dump, err := httputil.DumpRequest(r, true)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
}
log.Printf("%s", dump)
}
I have an android app that have a login form for student, and I want to check the student credential at web api depending on the stored data in sql server
I have searched the web and watch many videos that talking about many scenarios and nothing helped me.
All I want is a custom validation for my rest service (so I should send the credential for each request)
What should I do at asp.net web api service
how I can implement that at android application
Seems you didn't search for "Web API Token Based Authentication" ;) Anyhow what you need to implement is very simple.
You need to use OAuth 2.0 Resource Owner Credentials Flow which means that you want to provide the username/password only once for a specific endpoint i.e(/token) and then you if the username/password valid you obtain something called Bearer Access Token.
This token is valid for specified period and you can configure this in your Web API.
Once you obtain the access token, you need to store it securely in your android app, then you keep sending it with each request to your web api protected end points using the Authorization header (Bearer scheme(.
I've written very detailed post which covers your scenario 100%. Please check the post Token Based Authentication and let me know if you need further help.
I have used basic authentication for security,so I should provide the base64 encoding of
username:password
in header for each request as the following
authorization: Basic 'encoded username:password
httpGet.setHeader("Authorization", "Basic "+encodeUsernameAndPassword());
At the server side I have implemented message handler
public class BasicAuthenticationHandler : DelegatingHandler
{
public readonly IAuthenticationService authService;
public BasicAuthenticationHandler(IAuthenticationService service)
{
this.authService = service;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
AuthenticationHeaderValue authHeader = request.Headers.Authorization;
if (authHeader == null || authHeader.Scheme != "Basic")
{
return Unauthorized(request);
}
string encodedCredentials = authHeader.Parameter;
var credentialsBytes = Convert.FromBase64String(encodedCredentials);
var credentials = Encoding.ASCII.GetString(credentialsBytes).Split(':');
if (!authService.Authenticate(credentials[0], credentials[1]))
{
return Unauthorized(request);
}
string[] roles = null;//todo
IIdentity identity = new GenericIdentity(credentials[0], "Basic");
IPrincipal user = new GenericPrincipal(identity, roles);
HttpContext.Current.User = user;
return base.SendAsync(request, cancellationToken);
}