i'm trying to do a post request but all the time i get this error
Uncaught Error: XMLHttpRequest error.
i' working on dartpad on line and i'm using the package http.dart .I don't get the problem despite i post a json format i dont understand why the error is with the xml ?!
this my code :
import 'package:http/http.dart' as http;
void main() async {
// This will be sent as form data in the post requst
var map = new Map<String, dynamic>();
map['username'] = '**********';
map['password'] = '**********';
final response = await http.post(
Uri.parse('************'),
body: map,
);
print(response.body);
}
I suggest the following:
Verify that your URI is correct, I tried your code on DartPad with a simple GET request onto a Free API I found on the web and I get no errors
Verify that your endpoint has no weird CORS errors with another client (e.g. postman or Dio, see below)
Verify that you don't have weird cache values onto your machine. Doing a flutter clean && flutter pub get might help
Consider using Dio (pub.dev) as your http client as the dart's inner http package isn't quite ready for production imho.
Related
I have a dart server
httpServer = await HttpServer.bind(InternetAddress.anyIPv4, myPort);
and the client should send a post request with some json data in it's body,
how to read that body
..addRouter(fileAddedToShareSpaceEndPoint, HttpMethod.POST,
(request, response) {
//? here make a provider to handle peer share space items then update the items if the viewed items are for the updated peer
var headers = request.headers;
print(headers);
})
I got some answers saying that you can use the following code but I'am getting an error with both
var body1 = await request.transform(Utf8Decoder()).join();
// or
var body2 = request.transform(utf8.decoder).join();
and I am already have a full server setup and it's running so I don't wanna use other library like shelf or other thing because it's gonna be a lot of migration work
I have built interceptors around dio for error handling,logging and cache. I found some other packages like cached_network_image, advance_pdf_viewer use dart.dev's http client.
I want to make same requests processed from cached_network_image, advance_pdf_viewer from dio's client so that custom error messages are displayed in UI which provides uniformity.
Future<Dio> _getDio() async {
final dio = Dio()..options.baseUrl = ApiEndPoints.base;
dio.interceptors.addAll([
DioCachingInterceptor(
connectivity,
),
DioAppInterceptor(),
DioLoggingInterceptor(),
]);
return dio;
}
Any Ideas??
I am building a book app with Flutter for Android and iOS. I am using Google Books API to retrieve book data, but I have noticed something strange which I dont understand. If we look at the book data displayed in chrome browser (https://www.googleapis.com/books/v1/volumes/b3GuDwAAQBAJ), we can see that the content (eg. field categories) is different than what I get when calling http response and printing out it's body. In addition to that, it also seems like unicode characters (eg. from description) are not sent.
The code that I'm using to get the API data can be seen below:
Response result = await http.get(Uri.parse(url), headers: {'content-type': 'application/json; charset=utf-8'});
if (result.statusCode == 200) {
final jsonResponse = jsonDecode(utf8.decode(result.bodyBytes));
if (jsonResponse["totalItems"] == 0) {
return List.empty();
}
//this prints out the content in above image
print(result.body.toString());
final booksMap = jsonResponse['items'];
List<dynamic> books = booksMap.map((i) => Book.fromJson(i)).toList();
return books;
It seems that https://www.googleapis.com/books/v1/volumes/b3GuDwAAQBAJ gives different data than your usual search query (eg. https://www.googleapis.com/books/v1/volumes?q=isbn:9780143123231). I do not know the reason why.
You can see the API response in raw form due to which unicode are present
Raw Form image from browser
but when you get api response you can parse into json, By parsing json that unicodes are removed and data is in proper format
if you use json Formatter extension in chrome you can see that the data in chrome in Json form and the response from api when you are hitting api by code are same.
Data in Json Form in Browser
in the application code , you set headers: {'content-type': 'application/json; thats why u received Json data code. and its not problem because you will use this data into your application,
you can see more content types here
Blockquote
I am using the http package to call my API, but every request takes 8+ seconds to complete.
I have tried calling the same route via browser and postman and I get the response in less than a second. Also, I can assure that there is no issue with my internet connection.
class ApiRest {
Future<List<Product>> getProducts() async {
final apiResponse = await http.get(Uri.parse('some route'));
final resBody = jsonDecode(apiResponse.body);
return resBody['products']
.map<Product>((product) => Product.fromJson(product))
.toList();
}
}
Additionally, I tried applying the approach recommended by this answer, using the HTTP Client(), which didn't make a difference either.
Is there anything I am doing wrong or inefficient?
Lastly, the latest version of the http package for Flutter is currently 0.13.4. Do you think that the issue might be with this package? Or it might not be stable enough?
So I upgraded my IDE and SDK and now the following code doesn't work anymore. I am adding some text here to try to get around this sites fascist validation on posts it's pretty aggressive.
String URL = "http://www.google.com";
Future future = client.getUrl(Uri.parse(URL))
.then((HttpClientRequest request) {
return request.close();
}).then((HttpClientResponse response) {
print('Status code: ${response.statusCode}');
print('Headers\n${response.headers}');
});
});
I am getting the following exception now.
Uncaught Error: Bad state: No elements
Stack Trace:
Any ideas?
Works for me using Dart 0.6.3.3_r24898 on Windows.
Are you sure this is all the code you have? In the stack trace I see WebSocketImpl, are you using WebSockets?