Dio package header authorization token details print flutter - json

i want to print details of a user and I have user bearer token I tried but it throws a 302 error
Future fetchUsers() async {
Dio dio = Dio();
dio.options.headers["Authorization"] =
"Bearer 52|Umoe5JKgwYKoLacx8m2NtO3TJZa36iIqTh7KW3QR";
dio.options.followRedirects = false;
Response response = await dio.post("http://52.90.175.175/api/user/get");
print(response);
This is my json

Related

Flutter: How do I get List<String> from the JSON response?

I want to do feature follow this https://amazevlley.blogspot.com/2019/03/listview-sort-by-name-in-flutter.html in my application but I can't get the List< String> from this function.
Future<String> getJSONData() async {
var url = "http://.......:7000/";
// Await the http get response, then decode the json-formatted response.
var response = await http.get(url);
if (response.statusCode == 200) {
var jsonResponse = json.decode(utf8.decode(response.bodyBytes));
setState(() {
data = jsonResponse['data'];
});
print('jsonResponse: $jsonResponse.');
} else {
print('Request failed with status: ${response.statusCode}.');
}}

Unable to post a http request with json body because jsonEncode method from 'dart:convert' package adding escape character

I am trying to make an http post request using http/http.dart package with a JSON body. For that I am trying to convert a Map to JSON using jsonEncode (dart:convert package) but unable to do so as jsonEncode is adding escape character during conversion which makes the JSON string an invalid JSON for post.
Future postData(Map data) async {
Map<String, String> headers = {"Content-type": "application/json"};
var body = jsonEncode(data);
http.Response response = await http.post(url, headers: headers, body: body);
if (response.statusCode == 201) {
print("Customer creared");
} else {
print(response.statusCode);
}
}
When I am debugging above code the value for body is coming as below:
body = {\"first_name\":\"Manish\",\"last_name\":\"Kumar\",\"phone_numebr\":\"9123456789\",\"seal\":\"manne\"}
So here I can see an extra escape character being added to the json string which is making it hard to make an http post request with json body.
I tried making http post request by directly placing this string and it worked fine. Code below:
http.Response response = await http.post(url, headers: headers, body: '{"first_name":"Manish","last_name":"Kumar","phone_numebr":"9123456789","seal":"manne"}');
Can someone please help me converting a Map to json without escape characters?
Finally I got the answer.
I created a dataTest variable as below:
final dataTest = {
'first_name': firstName,
'last_name': lastName,
'seal': seal,
'phone_number': phoneNumber
};
Here firstName, lastName, seal and phoneNumber are of string type.
Now call,
postData(dataTest);
Future postData(dynamic data) async {
Map<String, String> headers = {"Content-type": "application/json"};
http.Response response = await http
.post(url, headers: headers, body: json.encode(data));
if (response.statusCode == 201) {
print("Customer creared");
} else {
print(response.statusCode);
}
}
So here the key is to call json.encode method on dynamic type and then pass it to the body parameter of http.post.

Get Request Status code: 400 Swift

i got code error **status code: 400*
URL: https://conversation.8villages.com/1.0/contents/articles?state=published }
{ status code: 400, headers {
Connection = "keep-alive";
"Content-Length" = 2;
"Content-Type" = "application/json";
Date = "Tue, 11 Apr 2017 07:49:13 GMT";
Server = nginx;
} }
2 bytes
SUCCESS
JSON: {
}
my json is result SUCCESS but wht not show my DATA?
actually i get request method Alamofire with Consumer Key, Consumer Secret, Token Key and Token Secret. like this :
let params: HTTPHeaders = ["oauth_consumer_key":"*****",
"oauth_consumer_secret":"*****",
"oauth_token_key":"*****.",
"oauth_token_secret": "*****",
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp_key" : "1491366048",
"oauth_version": "1.0"] as [String : Any] as! HTTPHeaders;
Alamofire.request("https://conversation.8villages.com/1.0/contents/articles?state=published", method: .get, headers: params).responseJSON { response in
print("test", response.request!) // original URL request
print("ini responseny", response.response!) // HTTP URL response
print("test", response.data!) // server data
print("test", response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
how to get my data API ??
Please keep in mind :
400 Bad Request : The server cannot or will not process the request
due to something that is perceived to be a client error (e.g.,
malformed request syntax, invalid request message framing, or
deceptive request routing).
For a better understanding check : this

Could not decode token: The token ###

I'm using Laravel 5.3 as an API for my iOS app. When I try to make HTTP calls with headers and parameters I get this 401 error:
message = "Could not decode token: The token
\"Optional(\""eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjUsImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDAwXC9hcGlcL2F1dGhcL3Bvc3RMb2dpbiIsImlhdCI6MTQ4MDUzNzQxOCwiZXhwIjoxNDgwNTQxMDE4LCJuYmYiOjE0ODA1Mzc0MTgsImp0aSI6ImMyZmYxNzI5N2U5OGU4MzkzYzZkZWRmNTZlN2ZkMzNkIn0.u6sQqlq5k-B5jhZ7EymkXLlcTIQ-i7X_83an5irwTss\"" is an
invalid JWS";
"status_code" = 401; }
This is the code that makes the HTTP request:
let headers = ["Authorization":"Bearer \(token)"]
request(url! , method: .get, parameters: nil, encoding: JSONEncoding.default , headers: headers )
.responseJSON { response in
print("RESPONSE \(response)")
I did some googling and found a package to encode JWT called JWTDecode.swift. Here is the link to the code: https://github.com/auth0/JWTDecode.swift. I still couldn't figure out how to solve this issue.
change
let headers = ["Authorization":"Bearer \(token)"]
to something like
guard let token = token else { return }
let headers = ["Authorization":"Bearer \(token)"]
otherwise you are sending Optional(<token>) instead of <token>.

HttpBuilder accessing secured link https

I am using this code for GETting a JSON object from the URL using Groovy: the URL that I use is a HTTPS URL so when I test the code I get a 403 error, after Google it I understand that I need to use a HttpBuilder SSL but I don't understand how can I do it.
the code is :
def getJson(Integer id) {
def adress = new HTTPBuilder("https://api.XXXY.com")
def path="/vls/v1/etudiants/${id}?b=my&apiKey=99990"
//Get request
adresseServeur.request(Method.GET, JSON) {
uri.path = path
headers.Accept = 'application/json'
// success response handler
response.success = { resp, json ->
retourJson = json
}
// failure response handler
response.failure = { resp ->
println "Unexpected error: ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"