Flutter: How to http POST image to Microsoft Cognitive Services - http

I am trying to POST an image taken from the camera to Microsoft Cognitive Service's Face API (using the Face - Detect method). However, when I try it returns the 'Response 415':
{
"error": {
"code": "BadArgument",
"message": "Invalid Media Type."
}
}
Here is my code for this method:
final bytes = image.readAsBytesSync();
var uri = Uri.parse("https://australiaeast.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false");
var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile.fromBytes('url', bytes, contentType: new MediaType('image', 'jpeg'));
request.headers['Ocp-Apim-Subscription-Key'] = "9c261636281d42c0947d89fe3982df73";
request.headers['Content-Type'] = "application/octet-stream";
request.files.add(multipartFile);
var response = await request.send();
print(request);
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
}
I used the Flutter Image Picker plugin to take the picture and get it to show up fine on the screen. All other operations I've tried with Microsoft Cognitive Services work fine - it is only uploading this image that is giving me problems.

I think you don't need a MultipartRequest but just a Request and assign the bodyBytes property:
final bytes = image.readAsBytesSync();
var uri = Uri.parse("https://australiaeast.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false");
var request = new http.Request("POST", uri)
..headers['Ocp-Apim-Subscription-Key'] = "9c261636281d42c0947d89fe3982df73"
..headers['Content-Type'] = "application/octet-stream"
..bodyBytes = bytes;
var response = await request.send();
print(request);
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});

Related

Firebase short URLs not redirecting

I created a Google Sheet that uses a Google Script to generate short URLs via Firebase API.
This is the code in the Google Script
function URLShortener(longURL) {
var body = {
"dynamicLinkInfo": {
"domainUriPrefix": "https://go.example.com",
"link" : longURL
},
"suffix": {
"option": "SHORT"
}
};
var key = 'xxxxxxx'
var url = "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=" + key;
var options = {
'method': 'POST',
"contentType": "application/json",
'payload': JSON.stringify(body),
};
var response = UrlFetchApp.fetch(url, options);
var json = response.getContentText();
var data = JSON.parse(json);
var obj = data["shortLink"];
return obj;
Logger.log(obj)
}
The script works and it generates URLs similar to https://go.example.com/Xdka but these link redirect to https://example.com/Xdka instead of the actual URL that is sent, e.g. https://example.com/final_url.
If I try to generate these short links from the Firebase dashboard the same happens.
Did I misunderstand how these short URLs work or am I missing something?

How do I set headers on Flutter/Dart http Request object?

I need a way to set the headers of the dart http Request object to application/JSON.
I want to build a Request object to send to my backend API. I set the body to my JSON object, but when it gets sent, it defaults the headers to text/html instead of application/json.
I have tried using the built-in method
http.post(url,dynamic body);
but unfortunately this method places the body in the parameters of the URL and I need it in the actual body of the request.
So instead I built an http Request object, and manually set the URL and body but like I said, it sets the headers to text/html.
I have read the docs for https://pub.dev/documentation/http/latest/http/Request-class.html, but unfortunately, I haven't found a way to set the headers.
postRequest(uri) async {
Uri url = Uri.tryParse("https://ptsv2.com/t/umt4a-1569012506/post");
http.Request request = new http.Request("post", url);
request.body = '{mediaItemID: 04b568fa, uri: https://www.google.com}';
var letsGo = await request.send();
print(letsGo.statusCode);
}
Much thanks for any possible solutions!
Ps. this is my first ask on Stack Overflow so I apologize if I made any errors in posting.
Solved!
postRequest(uri) async {
Uri url = Uri.tryParse("https://ptsv2.com/t/umt4a-1569012506/post");
http.Request request = new http.Request("post", url);
request.headers.clear();
request.headers.addAll({"content-type":"application/json; charset=utf-8"});
request.body = '{mediaItemID: 04b568fa, uri: https://www.google.com}';
var letsGo = await request.send();
print(letsGo.statusCode);
}
I was having some issues with the Request object default setting the encoding.
By manually specifying utf-8, the server I am contacting accepts it.
for the post or get any request you can Add Header like this -
var permAddUrl = 'your requested url';
var bodyParameters = {
'Email': email,
'MobileNo': mobileNumber,
};
await http.post(
requesturl,
headers: { 'Content-Type': 'application/x-www-form-urlencoded',
"Authorization":"$token",
},
body: bodyParameters,).then((response) {
var data = json.encode(response.body);
print(data);
setState(() {
if(response.statusCode == 200){
//var statesList = data['data'];
UtilAction.showSnackBar(context, " Details Submitted Successfully");
}
});
});

Actions on Google - Receiving 200, but no notification

I am using a webhook and c# to fulfill my logic within an Action.
I have subscribed to two intents, and have captured the "UpdateUserId".
Here is the notification payload
{
"customPushMessage": {
"target": {
"userId": "ABwppHFW6M9ASVqbKFBigM8N0mgssCJmPlwarmgzil_Nk_YsdZ1evzTAggEh0aEsctjOIYg2uHc8n7KfzNuHLuJoirXW",
"intent": "NotificationIntent",
"argument": {
"rawText": "Notification Argument Raw Text",
"textValue": "Notification Argument Text Value",
"name": "Notification Argument"
},
"locale": "en-US"
},
"userNotification": {
"title": "Notification Title",
"text": "Notification Text"
}
}
}
I am sending my notification using the following code blocks
private static async Task<string> GetAccessTokenFromJsonKeyAsync(string jsonKeyFilePath, params string[] scopes)
{
using (var stream = new FileStream(jsonKeyFilePath, FileMode.Open, FileAccess.Read))
{
return await GoogleCredential
.FromStream(stream) // Loads key file
.CreateScoped(scopes) // Gathers scopes requested
.UnderlyingCredential // Gets the credentials
.GetAccessTokenForRequestAsync(); // Gets the Access Token
}
}
public async Task<HttpResponseMessage> SendNotificationMessage(ProactiveMessage proactiveMessage)
{
try
{
var accessToken = await GetAccessTokenFromJsonKeyAsync("key.json", "https://www.googleapis.com/auth/actions.fulfillment.conversation");
var serialized = JsonConvert.SerializeObject(proactiveMessage);
var payload = "{\"customPushMessage\": " + serialized + "}";
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(payload, Encoding.UTF8, "application/json");
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var httpResponseMessage = await _httpClient.PostAsync($"{_hostUrl}", httpContent);
Console.WriteLine(httpResponseMessage.IsSuccessStatusCode ? "Successfully sent notification message." : $"Failed to send notification message with {httpResponseMessage.StatusCode}.");
return httpResponseMessage;
}
catch (Exception ex)
{
Debug.WriteLine($"Google Assistant Service: Failed to send notification message with exception: {ex.Message}");
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
The method returns a 200 Response. However, a notification never shows up on my phone.
I am not sure what my next steps for debugging are.
Since notifications are stil not public, is this a common issue?
I had the same issue. I received 200 status code but no notifications arrived at the target device.
I tried it again in approximately 2 days and it worked with no problems and have been working ever since.
The only explanation I could come up with is that there is some configuration running in the background.

Dart: HTTP GET with Header

I'm working on creating a Flutter application that works with LIFX. I'm trying to follow their instructions here, but I'm having issues adding a header to my HTTP GET request.
TestHttpGet() async {
var httpClient = new HttpClient();
var header = "Bearer $token"; //token hidden
var url = 'https://api.lifx.com/v1/lights/all/state';
String result;
try {
var request = await httpClient.getUrl(Uri.parse(url));
request.headers.set("Authorization", header);
var response = await request.close();
if (response.statusCode == HttpStatus.OK) {
var json = await response.transform(UTF8.decoder).join();
print(json);
var data = JSON.decode(json);
result = data['brightness'].toString();
} else {
result =
'Error getting response:\nHttp status ${response.statusCode}';
}
} catch (exception) {
result = 'Failed parsing response';
}
This returns with Error getting response: Http status 404. I've tried various ways of request.headers .set .add [HttpHeaders.Authorization] = "header" all return with a 404. Any advice would be appreciated.
You can pass a Map<String, String> to the http.get call as the headers parameter like this:
await httpClient.get(url, headers: {
'Authorization': 'Bearer $token',
});
In order to set headers you can't set the entire variable since it is set as final. What you need to do is set the value of the individual array items which are also known as the individual "headers" in this case.
For example :
http.Request request = http.Request('GET', uri);
request.headers['Authorization'] = 'Bearer $token';
I believe dart makes all the fields of a HttpHeader to lowercase.
https://github.com/flutter/flutter/issues/16665
The argument for that is because "Field names are case-insensitive". (otherwise it is not HTTP compliant)
https://www.rfc-editor.org/rfc/rfc2616#section-4.2
Let me know if you found a workaround for this.

how can I pragrammatically insert data in google analytics

Can you please tell me what is the wrong with the below code for programmatically inserting the pageview in google analytics.
Code is not inserting pageview.
var request = (HttpWebRequest)WebRequest.Create("http://www.google-analytics.com");
request.Method = "POST";
// the request body we want to send
var postData = new Dictionary<string, string>
{
{ "v", "1" },
{ "tid", "UA-XXXXXX-1" },
{ "cid", "555" },
{ "t", "pageview" },
{"dh","www.pomroofing.com"},
{ "dp", "/phone/123/456/789/1" },
{ "dt", "homepage" },
};
var postDataString = postData
.Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key,
HttpUtility.UrlEncode(next.Value)))
.TrimEnd('&');
// set the Content-Length header to the correct value
request.ContentLength = Encoding.UTF8.GetByteCount(postDataString);
// write the request body to the request
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postDataString);
}
try
{
var webResponse = (HttpWebResponse)request.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
throw new HttpException((int)webResponse.StatusCode,
"Google Analytics tracking did not return OK 200");
}
}
catch (Exception ex)
{
// do what you like here, we log to Elmah
// ElmahLog.LogError(ex, "Google Analytics tracking failed");
}
please help, or is there any api for this.
Try testing your full request string directly into a Browser. A short request like that can also be sent with a GET.
Check real-time reports to see if its showing up or not. (I tested this)
http://www.google-analytics.com/collect?v=1&tid=UA-XXXX-X&cid=555&t=pageview&dh=www.pomroofing.com&dp=/phone/123/456/789/1&dt=homepage
No there is no API for this.
BTW you are missing /collect in the url :)

Resources