Flutter data-raw in http PUT - flutter

I have this sample code
curl --request PUT \
--url someurl/test.png \
--header 'AccessKey: MY_API_AccessKey' \
--header 'Content-Type: application/octet-stream' \
--data-binary #myimage.png
How do I get this done in Flutter?

You did not mention where your image you are trying to upload does come from. So I supposed that is coming from local images. The code would then look the following (when using http package).
import 'package:http/http.dart';
void main() {
// example when loading image from assets
final image = Image.asset('graphics/background.png');
put(Uri.parse('someurl/test.png'), headers: {
'AccessKey': 'MY_API_AccessKey',
'Content-Type': 'application/octet-stream'
}, body: image.toByteData());
}

Related

Flutter receives 422 response from Fastapi when posting a PNG file

I have created a working localhost API with FastAPI. The POST takes a PNG, does some image processing and returns a PNG as expected when I click the 'try it out' button in the FastAPI generated docs:
The curl post command shows as follows:
curl -X 'POST' \
'http://localhost:8345/api/predict' \
-H 'accept: application/json' \
-H 'Content-Type: multipart/form-data' \
-F 'file=#test_img.png;type=image/png'
The image File is successfully retrieved from the image picker library. (Where the image1 object has been initialized as File image1; in the app page's class.
Future getImage() async {
var imageTmp = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
image1 = imageTmp;
print('Image Path $image1');
});
}
I tried to emulate the API call with the below function in Flutter.
doUpload() {
/*
curl -X 'POST' \
'http://192.168.178.26:8345/api/predict' \
-H 'accept: application/json' \
-H 'Content-Type: multipart/form-data' \
-F 'file=#test_img.png;type=image/png'
*/
var request = http.MultipartRequest(
'POST',
Uri.parse("http://<my locally hosted ip>:8345/api/predict"),
);
Map<String, String> headers = {"Content-type": "multipart/form-data"};
request.files.add(
http.MultipartFile(
'image',
image1.readAsBytes().asStream(),
image1.lengthSync(),
filename: 'filename',
contentType: MediaType('image', 'png'),
),
);
request.headers.addAll(headers);
print("request: " + request.toString());
request.send().then((value) => print(value.statusCode));
}
When I run the doUpload() function, a POST is successfully sent to the localhost API, but it returns a 422 error 'unprocessable entity'.
What I tried:
I tried to set the image type in doUpload to jpg, jpeg, but I keep getting a 422 error.
I tried looking up where the image_picker is supposed to store the temporary file to see if it's stored correctly, but when I look at the generated filepath, I don't see the actual file and tmp folder:
filepath: File: '/data/user/0/<my package name>/cache/image_picker3300408791299772729jpg'
looking at my local UI filepath, I see:
It shows no folder named cache, so I can't inspect it like this. However, the image picker saves it with a jpg at the end (not .jpg, is this normal?)
I also tried adding this debugger function to my fastAPI server.py, but I'm not sure how I can inspect the resulting data in the current flutter code:
https://fastapi.tiangolo.com/tutorial/handling-errors/#use-the-requestvalidationerror-body
The resulting value has properties like statusCode and reason, but I don't see a full json output option.
To mimic that curl command exactly, use this: (I've used the convenience constructor for simplicity)
final request = http.MultipartRequest(
'POST',
Uri.parse('http://<my locally hosted ip>:8345/api/predict'),
);
request.files.add(
await http.MultipartFile.fromPath(
'file', // NOTE - this value must match the 'file=' at the start of -F
image1.path,
contentType: MediaType('image', 'png'),
),
);
final response = await http.Response.fromStream(await request.send());
print(response.body);

The argument type 'Set<String>' can't be assigned to the parameter type 'Map<String, String>'

I'm trying to create an user authentication system using Auth0 in my Flutter app. The Auth0 REST documentation gave an example of cURL but I didn't find any flutter package which does the job of cURL. So, I used http.
Here's the code:
Future<String> getToken(String userId) async {
final response = await http.post(
Uri.parse('https://my-auth0-subdomain.auth0.com/oauth/token'), // I used my real subdomain
body: jsonEncode({
'grant_type=client_credentials',
'client_id=my_project_client_id', // I used my real client id
'client_secret=my_project_client_secret', // I used my real client secret
'audience=https://my-auth0-subdomain.auth0.com/api/v2/' // I used my real subdomain
}),
headers: {
'content-type: application/x-www-form-urlencoded'
},
);
final token = jsonDecode(response.body)["access_token"];
return token;
}
This gives me an error that The argument type 'Set<String>' can't be assigned to the parameter type 'Map<String, String>'. on line 10 (headers: {...}). I can resolve this error by using headers: {'content-type': 'application/x-www-form-urlencoded'},.
But this then gives the error from Auth0 {"error":"access_denied","error_description":"Unauthorized"}. The API is set up properly, because on running
curl --request POST \
--url 'https://my-auth0-subdomain.auth0.com/oauth/token' \
--header "content-type: application/x-www-form-urlencoded" \
--data grant_type=client_credentials \
--data 'client_id=my_project_client_id' \
--data client_secret=my_project_client_secret \
--data 'audience=https://my-auth0-subdomain.auth0.com/api/v2/'
it returns a "access_token", "scope", "expires_in" and "token_type".
Please help. It's very important.
Thanks in advance :)
Try to send data as url encoded using :
Map<String, String> myBody= {
'grant_type' : 'client_credentials',
'client_id' : 'my_project_client_id', // I used my real client id
'client_secret' : 'my_project_client_secret', // I used my real client secret
'audience ' : 'https://my-auth0-subdomain.auth0.com/api/v2/' // I used my real subdomain
};
Future<String> getToken(String userId) async {
final response = await http.post(
Uri.parse('https://my-auth0-subdomain.auth0.com/oauth/token'), // I used my real subdomain
body: myBody,
headers: {
'content-type: application/x-www-form-urlencoded'
},
);
final token = jsonDecode(response.body)["access_token"];
return token;
}

Convert cURL to Postman REST Call

How can I convert the following cURL command to a Postman rest call?
curl -X POST abc.com/input.import
-H 'content-type: application/x-www-form-urlencoded'
--data-urlencode "apiKey=123-456"
--data-urlencode "secret=12/her"
--data-urlencode "userKey=ApUR"
--data-urlencode "email=fakeImportedAccount#example.com"
--data-urlencode "profile={'firstName':'John','lastName':'Kira'}"
I tried the following:
URL: (POST) abc.com/input.import
Header: Content-Type:application/json
Body:
{
"apiKey":"123-456",
"userKey":"ApUR",
"secret":"12/her",
"email":"fakeImportedAccount#example.com",
"profile": {
"firstName":"John",
"lastName":"Kira"
}
}
EDIT: Raw-body format in Postman is required. Import creates the request in "x-www-form-urlencoded" form
The content-type is not application/json, it's application/x-www-form-urlencoded. What you need to do is in the body tab, select application/x-www-form-urlencoded. The content-type header will automatically be set for you. The just start adding the key/value pairs (the --data-urlencoded arguments)
UPDATE
Unrelated, but for those looking for a way to post JSON (which is very common), you would use the "raw" radio button and then you would manually type in the JSON to the window they provide. Also you would set the Content-Type header to application/json.
I finally found: I have to url-encode every key value and send it with Content-Type:application/x-www-form-urlencoded.
Header:application/x-www-form-urlencoded
Body:
{
"apiKey":"123-456",
"userKey":"ApUR",
"secret":"12%2Fher",
"email":"fakeImportedAccount%40example.com",
"profile":{
"firstName":"John",
"lastName":"Kira"
}
}

How to add request options in Angular 2?

I am trying to implement Auto search in Angular 2. I am trying to get data from API to populate in suggestion list. My API accepts headers with token. Below is a sample url:
curl -X GET --header 'Accept: application/json' --header 'Authorization: USERNAME PASSWORD' 'https://apsapi.azurewebsites.net/api/searchusers?searchstring=anil'
I am using npm ng2-completer plugin. This is my API Call:
constructor(private completerService: CompleterService, private translationService: AppTranslationService, private alertService: AlertService, private useronboardService: UserOnboard)
{
let options = new RequestOptions({ headers: new Headers() });
options.headers.set("Authorization",'Bearer0l4B9VpOnJMBzxMee8SQdU8pFW_L8wBAyQ');
let url = "https://arsapi.azurewebsites.net/api/searchusers?searchstring="
this.dataService = completerService.remote(url, 'userName', 'userName');
this.dataService.requestOptions(options);
}
I do not see any header attached in request. Below is image.
image
Above piece of code results in error and it tells: (method)RemoteData.requestoptions(requestOptions:any):void (TS)Expected 1 arguments but got 2.
Can someone help me to add header in the above code?

Cannot update password in WSO2 with a request

I'm trying to make a HTTP request to modify password from users that are stored into WSO2. I'm using the following request:
{
method: 'PUT',
url: domain + '/wso2/scim/Users/' + userId,
rejectUnauthorized: false,
headers: {
Authorization: 'Bearer ' + scimToken,
'Content-Type': 'application/json'
},
json: true,
body: {
userName : 'foo',
password : 'newPassw0rd'
}
}
But response returns a Java exception (I don't attach it here, because is too long and I think that doesn't have sense. Is related with Apache CXF).
I'm so new with SCIM and WSO2, so I think that I'm making a mistake in the request. Does anyone knows what's wrong?
Thanks!
create user with this request:
curl -v -k --user admin:admin --data '{"schemas":[],"name":{"familyName":"gunasinghe","givenName":"hasinitg"},"userName":"hasinitg","password":"hasinitg","emails":[{"primary":true,"value":"hasini_home.com","type":"home"},{"value":"hasini_work.com","type":"work"}]}' --header "Content-Type:application/json" https://localhost:9443/wso2/scim/Users
update password
curl -v -k --user admin:admin -X PUT -d '{"schemas":[],"name":{"familyName":"gunasinghe","givenName":"hasinitg"},"userName":"hasinitg", "password":"pwd123","emails":[{"value":"hasini#wso2.com","type":"work"},{"value":"hasi7786#gmail.com","type":"home"}]}' --header "Content-Type:application/json" https://localhost:9443/wso2/scim/Users/0032fd29-55a9-4fb9-be82-b1c97c073f02