Dart can not use a response.body as a String - php

long time listener first time caller.
I make an http request to an API, get a response which I convert to a String variable, which is then used in a subsequent http request however the second request fails.
In tracking the error of my ways I replaced the String variable with an actual string identical to the variable and it works. I got the API to echo back the string it is receiving and it echos back the String that should work as a variable.
here is the PHP function
elseif($_POST['action']=='get_defects'){
$data = get_aircraft_by_token($_POST['token']);
echo $data['Defects'];
}
here is the Dart function
Map<String, String> _getDefects = {
'action': 'get_defects',
'token': _token,
};
await _getHttpRequest(_getDefects);
print(_data);
var parsedJson = jsonDecode(_data) as List;
Defects._defects =
parsedJson.map((jsonItem) => DefectItem.fromJson(jsonItem)).toList();
Defects.saveDefectFile(Defects._defects);
}
}
here is the _getHttpRequest function called...
_getHttpRequest(Map<String, String> _httpRequest) async {
http.Response _response;
String _url = 'https://aircraftdata.flexihubs.com/API/interface.php';
Map<String, String> _header = {
'Content-Type': 'application/x-www-form-urlencoded'
};
_response = await http.post(_url, headers: _header, body: _httpRequest);
_data = _response.body;
}
if I replace
_token = response.body //does not work, response.body=='token'(true)
with
_token = 'token'; //this works no problem
it works? Printing response.body yields 'token', and echoing it yields 'token'; so I am guessing that there is something about the way the encoding works that I do not know, or something else?

Found the issue, thanks to the clue in the comments from Ro.
Solved with String.trim();
I guess there must have been a hidden trailing space that I was unaware of?

Related

flutter http post empty on server side

i try to send post request in flutter app like
static Future<List<dynamic>?> postData(data) async {
var body = json.encode(data);
Map<String, String> headers = {"Content-Type": "application/json"};
var url = Uri.http(Config.api, Config.endPoint);
var response = await client.post(url, headers: headers, body: body);
if (response.statusCode == 201) {
var data = jsonDecode(response.body);
return data;
}
return null;
}
this is data was sent
Map data = {
'database': 'school_control_ykt',
'table': 'tablets_helper',
'place': place,
'reason': reason,
'teacher': teacher,
'name': name,
'id_group': id_group
};
postData(data);
but in server side (php) $_POST are empty
i wanna know why $_POST are empty when a send the request in flutter app but in Postman request is send successfully and $_POST have data
enter image description here
Use MultipartRequest as API expect multipart/form-data. Something like this:
var request = MultipartRequest('POST', uri)
..fields = data
var response = await request.send();

How to send POST request from Flutter app to PHP server

I've tried to send a POST request from my Dart application to a PHP file on my server that only checks if $_POST['username'] is set, what happens is that the request seems to reach the server but the server refuses to "read it":
This is what the server sees when a request is received (seen by using: file_get_contents('php://input'))
{"username":"testUsername"}
but if I try to do something like:
isset($_POST['username'])
this always returns false.
Here is the method I use to send the POST request:
import 'dart:convert';
import 'package:http/http.dart' as http;
final String url = "my.domain.com";
final String unencodedPath = "/subfolder/myfile.php";
final Map<String, String> headers = {'Content-Type': 'application/json; charset=UTF-8'};
final Map<String,String> body = {'username': 'testUsername'};
Future<http.Response> makePostRequest(String url, String unencodedPath , Map<String, String> header, Map<String,String> requestBody) async {
final response = await http.post(
Uri.http(url,unencodedPath),
headers: header,
body: jsonEncode(requestBody),
);
print(response.statusCode);
print(response.body);
}
makePostRequest(url, unencodedPath, headers, body);
why does isset($_POST['username']) not see my POST sent value?
Your post request from flutter side is correct
isset($_POST['username'])
will return null as username is part of the json object, It would have worked if :
username = {"username":"testUsername"}
your request satisfied the above format.
To check for data you can do is :
if(!isset($_POST)){
// Takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json);
//add your check here that is $data["username"] as bellow
isset($data["username"])
}
You can also check for valid json using other methods.

Flutter Image upload issue

I am trying to upload image using below function everything working fine only is i want to send image in post and when i am trying get image getting nothing
This is for call API
Future getUploadImg(access_token,File _image) async {
print("Image: $_image");
String apiUrl = '$_apiUrl/user/upload-profile-image';
final length = await _image.length();
final request = new http.MultipartRequest('POST', Uri.parse(apiUrl));
request.headers['Accesstoken'] = "Bearer $access_token";
request.files.add(new http.MultipartFile('imagefile',_image.openRead(), length));
http.Response response = await http.Response.fromStream(await request.send());
print("Result: ${response.body}");
return json.decode(response.body);
}
My file that is passing to server is:
File: '/storage/emulated/0/Android/data/com.dotsquares.ecomhybrid/files/Pictures/c5df03f7-097d-47ca-a3c5-f896b2a38c086982492957343724084.jpg'
I got the result finally we need to pass string for image sharing my working code if anyone need for help:
Future getUploadImg(access_token,File _image) async {
print("Image: $_image");
var result;
var stream = new http.ByteStream(DelegatingStream.typed(_image.openRead()));
var length = await _image.length();
var uri = Uri.parse('$_apiUrl/user/upload-profile-image');
var request = new http.MultipartRequest("POST", uri);
request.headers['Accesstoken'] = "Bearer $access_token";
var multipartFile = new http.MultipartFile('imagefile', stream, length, filename: basename(_image.path));
request.files.add(multipartFile);
var response = await request.send();
print(" ===================response code ${response.statusCode}");
await response.stream.transform(utf8.decoder).listen((value) {
print(" =====================response value $value");
result = value;
});
return json.decode(result);
}
To avoid the following problems:
write failed
connection closed before ...
Flutter Doctor Error - SocketException: Write failed (OS Error: Broken pipe, errno = 32)
you need to add the correct parameters in the headers.
In my case, these problems occur with uploading images and sending base64 encoded requests. I solved it by adding the following 'connection' header: 'keep-alive':
final response = await this.httpClient.put(
url,
encoding: Utf8Codec(),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Accept': "*/*",
'connection': 'keep-alive',
'Accept-Encoding' : 'gzip, deflate, br',
},
body: body,
);

Android Kotlin Volley Post String with multiple variable

I would like to use POST method to post a string of username and password to a php page but I couldn't find the solution. Thus, i try to use JSONRequest method, but it always gave me the result of Response.ErrorListener. Please help to solve it.
Code for StringRequest:
UserNamePassword = "Name=aaa&Password=bbb"
val queue = Volley.newRequestQueue(this)
val stringRequest = StringRequest(Request.Method.POST, url,
Response.Listener<String> { response ->
// Display the first 500 characters of the response string.
println(response.toString())
}, Response.ErrorListener { println("That didn't work!") })
// Add the request to the RequestQueue.
queue.add(stringRequest)
Code for JSONRequest:
val jsonobj = JSONObject()
jsonobj.put("Name", "aaa")
jsonobj.put("Password", "bbb")
val que = Volley.newRequestQueue(this)
val req = JsonObjectRequest(Request.Method.POST,url,jsonobj,
Response.Listener {
response ->
//println(response["msg"].toString())
println("oooooooooooooookkkkkkkkkkkkkkkkkk")
}, Response.ErrorListener {
println("Error rrrrrrrrrrrrrrr")
}
)
que.add(req)
Trying it
...
}, Response.ErrorListener { error: VolleyError ->
println("Error $error.message")
}
...
we have the follow error message as you said us
06-07 20:46:17.317 10064-10064/com.gph.radiobutton I/Choreographer: Skipped 47 frames! The application may be doing too much work on its main thread.
06-07 20:46:17.320 10064-10064/com.gph.radiobutton I/System.out: Error com.android.volley.ParseError: org.json.JSONException: Value error of type java.lang.String cannot be converted to JSONObject.message
06-07 20:46:17.776 10064-10089/com.gph.radiobutton I/OpenGLRenderer: Davey! duration=1246ms; Flags=0, IntendedVsync=25096758012019, Vsync=25097541345321, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=25097546076936, AnimationStart=25097546158936, PerformTraversalsStart=25097546649936, DrawStart=25097546898936, SyncQueued=25097546932936, SyncStart=25097546989936, IssueDrawCommandsStart=25097547040936, SwapBuffers=25097910009936, FrameCompleted=25098004716936, DequeueBufferDuration=10218000, QueueBufferDuration=5455000,
Then we can see that the problem is another, e.g., an error do occur on your web service and you don't send them as a valid json to the application again.

Angular2 http.post won't send JSON data to API

I've been trying to figure this out for almost a day, with no luck.
I have a simple http.post request:
import { Component } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/toPromise';
#Component({
selector: 'SendPost',
})
export class SendPostComponent {
constructor(
private http:Http,
) {}
private urlPost:string = 'www.mydomain.com/api/order.php'
private addToBasket() {
var data = {
foo: "bar",
foo1: "another"
}
var postData = JSON.stringify(data);
let headers = new Headers({'Content-Type': 'application/json'}); //x-www-form-urlencoded
headers.append('Access-Control-Allow-Methods', "GET, POST, OPTIONS");
let options = new RequestOptions({ headers: headers });
this.http.post(
this.urlPost,
postData,
options
)
.toPromise()
.then((res) => {this.extractData(res)});
}
private extractData(res: Response) {
console.log('extractData:', res);
}
}
I striped the API endpoint to absolute minimum: no .htacces, just the php file this simple code:
<?php print_r(json_encode($_REQUEST)); die; ?>
I keep getting an empty array in return. However, if I change the code like this:
var data2 = 'foo=bar&foo1=another'
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
Then the $_REQUEST objects gets my data. What am I missing?
PHP $_REQUEST is:
An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE
and $_POST
An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.
PHP can't parse "application/json" data, the workaround is php wrapper, by using "file_get_contents('php://input')" you can fetch the data from request entity body in this way:
$body = file_get_contents('php://input');
$data = json_decode($body);
print_r($data); // here is what you need

Categories