I m trying to upload image using Multipart request using Dart/ Flutter.
but parameter not getting on serverside.
var request = http.MultipartRequest('POST', uri);
request.fields['access_token'] = token;
request.files.add(await http.MultipartFile.fromBytes(
'image', path.readAsBytesSync(),
contentType: MediaType('image', 'jpeg')));
request.headers['Content-Type'] = "multipart/form-data";
request.headers['access_token'] = token;
var response = await request.send();
It's likely that you're sending an empty payload. From the code snippet you've provided, it's possible that path.readAsBytesSync() wasn't able to return the File immediately. You can add an await keyword on your function to wait for the return value before proceeding to send the Request.
Related
Im trying to make post request in flutter as shown below
uploadImage() async {
print('inside uploadimage function');
WidgetsBinding.instance.addPostFrameCallback((_) => setState((){isLoading = true;} ));
final request = http.MultipartRequest(
"POST", Uri.parse('http://server/upload'));
final headers = {"Content-type":"multipart/form-data"};
request.files.add( http.MultipartFile('image1',
widget.imagefile1!.readAsBytes().asStream(),widget.imagefile1!.lengthSync(),
filename: widget.imagefile1!.path.split("/").last));
request.files.add(http.MultipartFile('image2',
imageFile!.readAsBytes().asStream(),imageFile!.lengthSync(),
filename: imageFile!.path.split("/").last));
request.headers.addAll(headers);
final response = await request.send();
http.Response res = await http.Response.fromStream(response);
print('statuscode:');
print(response.statusCode);
print(response.reasonPhrase);
}
as a response I get error 413 request entity too large but when I make a request through POSTMAN i can successfully make a request with status 200 OK. as shown below
I'm not able to figureout why this happening any help or suggestion on how to solve this will be highly appreciated thanks
I'm trying to receive the response on a http post but the response comes empty. I know its something basic but i can't make it work.
It should receive a JSON with some data, but the data doesn't come, probably its a problem on the reply part on my code.
Heres the code:
Future<void> _login2() async {
HttpClient client = new HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
String url = 'https://sistema.hutransportes.com.br/api/login.php';
Map map = {"user": "test", "pass": "123456"};
HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply); //should show the data from the http
}
I would recommend you to use the powerful library https://pub.dev/packages/dio
i am trying to sign a http request to aws api gateway in android using okhttp. i have more or less used the code in this stackoverflow question stackoverflow question
i use CognitoCachingCredentialsProvider() to get a credentialsProvider object. i then use getCredentials() to get the credentials. i then use the following: credentials.getAWSAccessKeyId(), credentials.getAWSSecretKey() and credentials.getSessionToken() to get the necessary keys and token. i use them in postman and am able to successfully execute the api gateway.
the request fails in android using okhttp, returning a code 403 with the message "Missing Authentication Token".
this is how i prepare the request: i build a DefaultRequest object, setting the endpoint and httpmethod. i then use AWS4Signer to sign the request, passing the credentials object as the signer.sign(defaultRequest, credentials) parameter.
i get a map of headers by calling getHeaders() on the defaultRequest. i create two lists, one called key for the key and one called value for the value. i then loop through the map, loading the keys and corresponding values into the two lists.
i then build my okhttp request as follows:
Request request = new Request.Builder()
.url(my ApiEndPoint)
.addHeader(key.get(0), value.get(0))
.addHeader(key.get(1), value.get(1))
.addHeader(key.get(2), value.get(2))
.addHeader(key.get(3), value.get(3))
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.post(body)
.build();
i notice the following:
in the headers map, key x-amz-security-token has a value ....ending in hKADF87VZ44w9IvZ1gU=
printing out the okhttp request, the key x-amz-security-token has a value .... ending in hKADF87VZ44w9IvZ1gU\u003d
the = is replaced by \u003d, could this be the problem? if so, how to prevent this?
otherwise, any help in solving this problem will be greatly appreciated.
thanks
managed to solve the problem. seems that assigning the headers to the OkHttp request was the problem. so here's my code:
i first get AWSSessionCredentials credentials. then:
AmazonWebServiceRequest amazonWebServiceRequest = new AmazonWebServiceRequest() {
};
String API_GATEWAY_SERVICE_NAME = "execute-api";
com.amazonaws.Request requestAws = new DefaultRequest(amazonWebServiceRequest, API_GATEWAY_SERVICE_NAME);
you can use either the service endpoint:
URI uri = URI.create("https://apigateway.eu-west-1.amazonaws.com");
or your api url (the invoke url for api as per Api Gateway console Stages option (The deployed api)):
String invokeUrl = "https://xxxx.execute-api.eu-west-1.amazonaws.com/yyy/zzzzz";
// using the invoke url
URI uri = URI.create(invokeUrl);
requestAws.setEndpoint(uri);
requestAws.setResourcePath(invokeUrl);
requestAws.setHttpMethod(HttpMethodName.POST);
now sign the request
AWS4Signer signer = new AWS4Signer();
signer.setServiceName(API_GATEWAY_SERVICE_NAME);
signer.setRegionName(Region.getRegion(Regions.EU_WEST_1).getName());
signer.sign(requestAws, credentials);
get the headers
// get map of headers
Map<String, String> headers = requestAws.getHeaders();
// create objects for the headers to add manually in OkHttp request builder
String x_date = null;
String x_token = null;
String authorization = null;
//get and assign values
for (Map.Entry<String, String> entry : headers.entrySet()) {
if (entry.getKey().equals("x-amz-security-token")) {
x_token = entry.getValue();
}
if (entry.getKey().equals("X-Amz-Date")) {
x_date = entry.getValue();
}
if (entry.getKey().equals("Authorization")) {
authorization = entry.getValue();
}
}
build the OkHttp request:
Request request = new Request.Builder()
.url(invokeUrl)
.addHeader("Content-Type", "application/json")
.addHeader("X-Amz-Date", x_date)
.addHeader("x-amz-security-token", x_token)
.addHeader("Authorization", authorization)
.post(body)
.build();
now make your OkHttp call.
hope this is helpful to someone.
In my Xamarin android application I need to make an api call to openweathermap to get current weather data according to the user's current location.
Here is my query string code:
url = "api.openweathermap.org/data/2.5/weather?lat=" +
_currentLocation.Latitude +
"&lon=" +
_currentLocation.Longitude +
"&APPID=" + openWeatherAPIKey
+ "&units=imperial";
Now in the method FetchUrlAsync I send the web request and retrieve the response json. Below is the code of the method:
async Task<JsonValue> FetchUrlAsync(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new System.Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (System.IO.Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
// Return the JSON document:
return jsonDoc;
}
}
}
I get a System.URIFormatException thrown on the first line of the method because the format of the uri is wrong. I checked other stack overflow questions and I think it might be because my url string does not start with a http:// or ftp. But I can't add http:// or ftp in front of the url string because that leads to an unrecognized server.
Any solution to this issue? Or does it not have to do with adding the http:// or ftp prefix?
I am able to get the access_token for the salesforce oath2. access token can expire after some time and after that we need to refresh the access token. But I am always getting "Bad Request" error in this code.
function getRefreshToken(refreshToken) {
var url = loginUrl + 'token';
var client = Ti.Network.createHTTPClient({
// // function called when the response data is available
onload : function(e) {
Ti.API.info("Received text: " + this.ResponseText);
alert(this.status);
alert(this.responseText);
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug(e.error);
alert(this.status);
alert(e.error);
},
timeout : 5000 //in milliseconds
});
//Prepare the connection.
client.open("POST", url);
client.setRequestHeader("content-type", "application/json");
//Send the request.
var param = 'grant_type=refresh_token&client_id=' + escape(clientId) + '&client_secret='+ escape(clientSecret) + '&refresh_token=' + escape(refreshToken);
Ti.API.info(param);
client.send(param);
}
am I missing something in this code? expected result is a json response with new access_token.
What the exact URL you send the request to? Also, you set the request content-type to be json, but seem to be sending a forms request, not a json formatted request, you probably need to change the content-type header to be "application/x-www-form-urlencoded"