Hello i am trying to make a http request in flutter for web, but I am having a lot of problems here.
Response for any request I am doing looks like this:
I am making requests like this:
Ok, I realised that if i decode response like this:
var responseBody = json.decode(utf8.decode(response.bodyBytes));
I get:
Still I don't have full key-value response and the status code
How can I get normal respone?
I think you you need to decode you response body with json.decode from dart:convert.
import 'package:http/http.dart' as http;
import 'dart:convert';
final response = await http.get('https://dog.ceo/api/breeds/image/random');
if (response.statusCode == 200) {
final Map<String, dynamic> responseMap = json.decode(response.body);
}
Related
There must be something wrong with my c# code. I am trying to download some Json from an Azure Blob. I can download the Json in Postman and from MS Edge however, using my code there are no apparent errors in the request but there is no content in the response. Presumably there is something wrong with my code.
async Task GetJson()
{
var request = new HttpRequestMessage
{
Method = new HttpMethod("GET"),
RequestUri = new Uri("https://xxx.blob.core.windows.net/trading/m5.json")
};
request.Headers.Add("Accept", "application/json");
request.SetBrowserRequestMode(BrowserRequestMode.NoCors);
var response = await http.SendAsync(request);
var json = await response.Content.ReadAsStringAsync();
}
This was asked on GitHub and apparently it is by design.
When you remove request.SetBrowserRequestMode(BrowserRequestMode.NoCors); line you will see the No 'Access-Control-Allow-Origin' header is present error.
Specifiying BrowserRequestMode.NoCors does not let you bypass the Browser security rules. It just simplifies the request headers.
I'm working on Flutter an app which will use Express based REST api. While implementing Cookie based sessions, I wanted to retrieve cookies from app with basic auth request but somehow I can't retrieve cookies in response. When I make the same request from Postman, there is no problem, cookies are setted automatically.
I am using HTTP package to make request and code is quite straightforward as below.
void login(String username, String password) async {
var url = 'http://$username:$password#111.222.333.444:3333/auth';
var response = await http.get(url);
print('Response header: ${response.headers}');
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}
There is no cookie in header or body of response.
If you want to get cookie values from HTTP response in flutter
String rawCookie = response.headers['set-cookie']!;
int index = rawCookie.indexOf(';');
String refreshToken = (index == -1) ? rawCookie : rawCookie.substring(0, index);
int idx = refreshToken.indexOf("=");
print(refreshToken.substring(idx+1).trim());
You have to call 'set-cookie' in header:
var cookies = response.headers['set-cookie'];
http package
get and post actions are sending the request without cookies so you should put the cookies manually like this:
Response response = await get(url, headers: {'cookie': 'session_id=ufe1nfq69mdi67pnql6n1cs3cv; path=/; HttpOnly='});
But there is an easy way to do that without putting cookies manually by requests package
import 'package:requests/requests.dart';
// ...
// For example post some login request
var url = "http://yourApilink";
var body = Map<String, dynamic>();
body["username"] = username;
body["password"] = password;
var request = await Requests.post(url, body: body);
request.raiseForStatus();
if(request.statusCode==200) {
//Successful
var statusJson = json.decode(utf8.decode(request.bytes()));
//....
// Example for get some other actions
var url = "http://yourApilink";
var request = await Requests.get(url);
request.raiseForStatus();
print(request.json()['userid']);
if(request.statusCode==200) {
//Successful
var statusJson = json.decode(utf8.decode(request.bytes()));
//....
I'm trying to parse a url image in order to turn it into Uint8 bytes and share across my share provider. When trying to consolidate my http response into bytes I get the following error The method 'consolidateHttpClientResponseBytes' isn't defined by my class. Here is the code I'm trying to use..... Please help!
Future<Null> shareImage() async{
var request = await HttpClient().getUrl(Uri.parse('network_image_url'));
var response = await request.close();
Uint8List bytes = await consolidateHttpClientResponseBytes(response);
}
Import this :
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
And you should be good
I have the following dart program:
import "dart:io";
import "dart:convert" show UTF8;
void main() {
HttpClient client = new HttpClient();
client.badCertificateCallback = (certificate, host, callbackPort) {
print("In bad certificate callback.");
return true;
};
client.getUrl(Uri.parse("https://www.self.signed.url.com/api")).then((HttpClientRequest request) {
print("In request callback.");
return request.close();
}).then((HttpClientResponse resp) {
print("In responce callback.");
});
}
This code makes a get request to a url. The url uses a self signed certificate, which results in an SSL error. To get around this I have set the badCertificateCallback of HttpClient to always return true, effectively accepting all certificates.
With this code I would expect to see following output:
In request callback.
In bad certificate callback.
In responce callback.
And then have the program exit. Instead I see:
In bad certificate callback.
In request callback.
And the program hangs. Any ideas on what I am doing wrong?
UPDATE: I have submitted a Dart bug as advised by some of the comments. It can be found here. If anything comes of that I'll put the results back into this.
It turns out that it has nothing with HTTPS to do, but with the handling of the HTTP protocol on the https://checkmate.fogbugz.com/api.xml server. The Dart HTTP stack send all headers field names in lower case. This is not handled correctly by the server.
The following code illustrates this:
import 'dart:io';
import 'dart:convert';
void main() {
SecureSocket.connect("checkmate.fogbugz.com", 443).then((socket) {
socket.write("GET /api.xml HTTP/1.0\r\n"
"host: checkmate.fogbugz.com\r\n"
"\r\n");
socket.listen((data) => print(UTF8.decode(data)));
});
}
No response is ever received. If host: is changed to Host: the response is received.
RFC 2616 section 4.2 states: 'Field names are case-insensitive.'
I started off by trying to use HTTPRequest in dart:html but quickly realised that this is not possible in a console application. I have done some Google searching but can't find what I am after (only finding HTTP Server), is there a method of sending a normal HTTP request via a console application?
Or would I have to go the method of using the sockets and implement my own HTTP request?
There's an HttpClient class in the IO library for making HTTP requests:
import 'dart:io';
void main() {
HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://www.dartlang.org/"))
.then((HttpClientRequest request) {
return request.close();
})
.then(HttpBodyHandler.processResponse)
.then((HttpClientResponseBody body) {
print(body.body);
});
}
Update: Since HttpClient is fairly low-level and a bit clunky for something simple like this, the core Dart team has also made a pub package, http, which simplifies things:
import 'package:http/http.dart' as http;
void main() {
http.get('http://pub.dartlang.org/').then((response) {
print(response.body);
});
}
I found that the crypto package was a dependency, so my pubspec.yaml looks like this:
name: app-name
dependencies:
http: any
crypto: any
You'll be looking for the HttpClient which is part of the server side dart:io SDK library.
Example taken from the API doc linked to above:
HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://www.example.com/"))
.then((HttpClientRequest request) {
// Prepare the request then call close on it to send it.
return request.close();
})
.then((HttpClientResponse response) {
// Process the response.
});