How to get redirect URL in dart/flutter? - flutter

I'm building an app that shows an image taken from source.unsplash. My request url is:
https://source.unsplash.com/random/`$widthx$height`
Then the service redirects to some specific image url picked fitting my width and height.
I can show the image with:
Image.network(url above),
but I cannot access the new redirected url for some other parts of my code which is really necessary. Is there a way to get it?
Thanks in advance
Something I'm searching for is like
Http.Response response = await Http.get(url);
print(response.finalRedirectURL);

It would be better if you use api.unsplash.com and not source.
If followRedirects is true, there's no way according to the docs to get the final redirected URL, so maybe post a github issue for this. See: https://pub.dev/documentation/http/latest/http/Response-class.html
The only way I see this happening is making followRedirects: false, will give you a response headers with location as a key that gives you the next redirect. You'd have to write a loop to keep going till the status code changes from 302 to something else.
Hope this helps.

For my own project, I was also not able to find any method from flutter/dart side.
However, I was able to find the location in response.headers. Maybe this can work.

Future<String?> getUrlLocation(String url) async {
final client = HttpClient();
var uri = Uri.parse(url);
var request = await client.getUrl(uri);
request.followRedirects = false;
var response = await request.close();
return response.headers.value(HttpHeaders.locationHeader);
}

Related

Post request flutter

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.

Google Books API not returning the same as displayed on browser (Flutter)

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

URL interpolation using Uri class

I'm having an issue with the Uri class, the code below used to work before the updates but now, the issue is that it uses a String instead of a Uri URL, I've been trying to update this interpolation to the newest standard with no success. This URL is simply getting data from Firebase with tokens from users that are signed in.
final response = await http.get("$_url.json?auth=$_token");
I already managed parse the main part of the url:
Uri _url = Uri.parse("https://my-project.firebaseio.com/example");
The final result used to be something like this:
https://my-project.firebaseio.com/example.json?auth=xLwOQ2GEQxPp0h0QD1foHgSyXR52
How do I interpolate this URL properly since I have one value that isn't static? (_token)
You should use the Uri.https constructor to create the Uri you then use with get.
For example
var uri = Uri.https('my-project.firebaseio.com', '/example', queryParameters: {'auth': _token})
See Uri.http documentation

json Fetch rerun

So i'm writting app in which i fetch data from air quality index webpage www.waqi.info and display it. So i got it working for one city but when i change city on popuplist how to recall api with different url. Tried something but it doesn't work. Now i have idea to save city in phone memory and then reruning app. Any clues how i can recall Http request for different city almost same url but how to recall http request from onchange. Im new to flutter and dart. Sorry for any stupidty
you have to use http 0.12.0+2 library to do API calls http library page
you can simply create a function which will fetch data
getData(city) async{
String url="YOUR_URL_HERE?city="+city;
var response=await http.get(url);
return response.body;
}
You can call this method from your onChanged
you can use a function to call api and pass city name as argument
like this
callApi(city) async{
String url="Url/${city}";
var response=await http.get(url);
return response.body;
}
and after getting response set data drom response to model object and then call setState()
which will reset your whole screen

Can I retrieve a file from server with GET in rest

Can I return a file with my get request? I want to return a word document to calling angularJS service through REST GET method. Not sure if it is even possible.
You're a bit light on detail, so I'm gonna be a bit light on answer.
A REST request is just... a request. The REST side of things is more the way URLs are defined that what actually happens in the request process itself, which is all still vanilla HTTP.
So, same as with any GET request, if you want to return binary data, set the headers appropriately (<cfheader>), then return the file (<cfcontent>).
So this is how I did it, luckily I got this:
http://smithcustomdev.com/2010/10/20/download-file-to-browser-using-cfscript/
All I have to do was make the method remote and listen to REST service
<cfscript>
private void function serveFile(string filePath){
var fileContent = fileRead(expandPath(filePath));
var context = getPageContext();
context.setFlushOutput(false);
var response = context.getResponse().getResponse();
response.reset();
response.setContentType("text/csv");
response.setContentLength(len(fileContent));
response.setHeader("Content-Disposition","attachment; filename=#listLast(filePath,'\')#");
var out = response.getOutputStream();
out.write(ToBinary(ToBase64(fileContent)));
out.flush();
out.close();
}
</cfscript>