How to format the url? - flutter

I want to format url. Here is an example:
Input:
www.google.com
or
google.com
Output:
https://www.google.com/
I need to format the url because I'm using a validator function that needs to check if the text is a url. When I type www.google.com or google.com it says it's not a url because it requires https at the beginning of the text.
My code:
validator: (value) {
if (value == null) {
return null;
}
if (Uri.parse(value).host.isEmpty) {
return "Please type a valid url";
}
},
Feel free to leave a comment if you need more information.
How to format the url? I would appreciate any help. Thank you in advance!

I have added some more conditions to your validator function :
validator: (value) => {
if (value == null) {
return null;
}
if (!value.startsWith("https://")) {
value = "https://" + value;
}
if (!value.startsWith("https://www.") && !value.startsWith("https://")) {
value = "https://www." + value.substring(8);
}
if (Uri.parse(value).host.isEmpty) {
return "Please type a valid url";
}
}

I would first sanitize the URL with something like:
String ensureScheme(String url) {
var uri = Uri.tryParse(url);
if (uri == null || !uri.hasScheme) {
url = 'https://$url';
}
return url;
}
which would add an https URL scheme only if no scheme is already present, thereby avoiding mangling URLs that use other schemes (e.g. file:///some/path, mailto:user#example.com, ssh://user#host.example.com, tel:+1-800-555-1212).
Additionally, note that your Uri.parse(value).host.isEmpty check is not quite correct:
Uri.parse will throw an exception if given unparsable input (e.g. ':'). You probably should be using Uri.tryParse instead.
An empty host does not necessarily imply an invalid URL. For example, all of the following would have an empty host:
file:///some/path
mailto:user#example.com
tel:+1-800-555-1212
(But maybe that's okay if you don't care about such URLs.)

Related

I wana have my application to fetch a html web page but i keep getting -400 whatever i try monkey c / garmin connect

even this exemple i found on the site of garmin has the same problem
https://developer.garmin.com/connect-iq/core-topics/https/
import Toybox.System;
import Toybox.Communications;
import Toybox.Lang;
class JsonTransaction {
// set up the response callback function
function onReceive(responseCode as Number, data as Dictionary?) as Void {
if (responseCode == 200) {
System.println("Request Successful"); // print success
} else {
System.println("Response: " + responseCode); // print response code
}
}
function makeRequest() as Void {
var url = "https://www.garmin.com"; // set the url
var params = { // set the parameters
"definedParams" => "123456789abcdefg"
};
var options = { // set the options
:method => Communications.HTTP_REQUEST_METHOD_GET, // set HTTP method
:headers => { // set headers
"Content-Type" => Communications.REQUEST_CONTENT_TYPE_URL_ENCODED},
// set response type
:responseType => Communications.HTTP_RESPONSE_CONTENT_TYPE_URL_ENCODED
};
var responseCallback = method(:onReceive); // set responseCallback to
// onReceive() method
// Make the Communications.makeWebRequest() call
Communications.makeWebRequest(url, params, options, method(:onReceive));
}
}
can some one please tel me what i am doing wrong
The return code -400 means "Response body data is invalid for the request type." according to the SDK specification.
You are requesting a response type of Communications.HTTP_RESPONSE_CONTENT_TYPE_URL_ENCODED but in your question you state that you are expecting HTML to be returned, which almost certainly can't be parsed as URL encoded form parameters.
The SDK does not seem to support HTML response types. Even if you omit the expected response type, the server will probably still send "application/html" and the SDK states that "If the Content-Type header from the response is not one of the known HTTP_RESPONSE_CONTENT_TYPE_* types, an error will occur", so I guess you're out of luck.
Maybe you can try to request HTTP_RESPONSE_CONTENT_TYPE_TEXT_PLAIN in order to get the server to return text instead of HTML, which you then could use somehow?

Why is Axios data undefined when stored in a variable?

I have the following code I am working on. This is implemented on a Vue app and uses a number of methods which each return with an Axios promise. I am trying to chain these so when a new review is submitted, the server checks if a movie exists already. If not, it creates a new movie. Then it should create a new review using postReview with a parameter of movieId. A movieId is required to create a new review. The methods checkMovieExists() and postMovie() both return a movieId as a response.
The problem is that when I log x.data() or y.data() into the console, the movieId is displayed correctly. However, if I assign x.data or y.data to movieId, it is undefined. This means I can't use it as a parameter to post a movie.
submit() {
let movieId = 0;
this.checkMovieExists(this.movie.imdb_id)
.then((x) => {
console.log(x.data);
if (x.data == 404) {
this.postMovie(this.movie.imdb_id, this.movie.original_title).then(
(y) => {
console.log(y.data); //Displays correctly
movieId = y.data;
console.log(movieId); //Displays as undefined
}
);
} else {
movieId = x.data;
}
})
.then(this.postReview(movieId));
},
(Btw, I am aware of the bug where a movie id is 404. This is my next task!)
I would advise you to stay away from callback hell and to use async/await.
async submit() {
let movieId = 0;
const checkMovieResponse = await this.checkMovieExists(this.movie.imdb_id);
if (checkMovieResponse.data == 404) {
const postMovieResponse = await this.postMovie(this.movie.imdb_id, this.movie.original_title);
movieId = postMovieResponse.data;
}
else {
movieId = checkMovieResponse.data;
}
await this.postReview(movieId);
}
Your problem should be fixed with my solution (there was an asynchronous issue with your code).
Your postMovie callback was executed after your checkMovie callback (causing an "undefined" (should be 0 by just reading your code) movieId in your postReview method).
If for some reasons, you cannot use async/await, here is your "fixed" code:
submit() {
this.checkMovieExists(this.movie.imdb_id)
.then((x) => {
if (x.data == 404) {
this.postMovie(this.movie.imdb_id, this.movie.original_title).then(
(y) => {
this.postReview(y.data)
}
);
} else {
this.postReview(x.data);
}
});
}
By the way, if the data from your Axios response is a number (for your identifier), I would advise you to use the === operator instead of the ==.
Good luck with your project!

Why is my cookie always null?

I don't get this. An hour ago it worked and all of a sudden I can't get back the cookie I just set. Under Chrome I can see that the cookie is actually there but if I try to get it back it's null:
private void setLoggedInCookie(String sessionId) {
String domain = this.getDomain();
Cookies.setCookie(ApiParameters.LOGIN_COOKIE, sessionId, expires, domain, "/", true);
String cookie = Cookies.getCookie(ApiParameters.LOGIN_COOKIE);
// Getting NOTHING from this ..
for (String string : Cookies.getCookieNames()) {
LOGGER.info("Cookie name: " + string);
}
if(cookie == null) {
throw new RuntimeException("Cookie is 'null'.");
}
}
private String getDomain() {
LOGGER.fine("Host name: " + Window.Location.getHostName());
String domain = Window.Location.getHostName().replaceAll(".*//", "").replaceAll("/", "").replaceAll(":.*", "");
return "localhost".equalsIgnoreCase(domain) ? "localhost" : domain;
}
What is happening?
You pass domain name "null". Browsers allow access only to cookies associated with the current page's domain. Since you are trying to access it from a page which is not "null", you can't get it.
Also, make sure you are trying to access it using SSL, since you set "secure" parameter to true.

How do I get the file name from HTTP header while downloading a file with Grails rest plugin?

I am using Grails Rest plugin to download a file from a server but how can I get hold of the suggested file name that is part of the http header field "Content-disposition"?
My code:
withHttp(uri:uri){
def logo = new Logo()
def status = get(path:path, query:[identity: identity]){ resp, body ->
if( resp.status == 200){
logo.contentType = resp.contentType
// logo.fileName = How?
logo.bytes = body.getBytes()
}
return resp.status
}
if(status == 200){
return logo
}
else{
log.warn("Failed to fetch logo ")
return null;
}
}
I can read the content type, byt how do I get the suggested file name?
Well, I figured out one way of doing it. Maybe not the nicest solution but it works for the most common scenarios.
EDIT: I have changed this code to use existing methods to parse elements and properties of a header value. Hopefully it will handle different header scenarios better. I am still not sure if the *filename parameter is handled correctly.
withHttp(uri:uri){
def logo = new Logo()
def status = get(path:path, query:[identity: identity]){ resp, body ->
if( resp.status == 200){
logo.contentType = resp.contentType
def contentDisposition = resp.getFirstHeader('Content-Disposition')
def element = contentDisposition?.elements.find{ it.name.equalsIgnoreCase('filename') || it.getParameterByName('filename')}
if(element)
logo.fileName = element.getParameterByName('filename')?.value ?: element.value
logo.bytes = body.getBytes()
}
return resp.status
}
if(status == 200){
return logo
}
else{
log.warn("Failed to fetch logo ")
return null;
}
}

How to get the name in facebook and silverlight?

I've been trying to get the name and only the name.
Like this shows everything:
fb.GetAsync("me", (val) =>
{
if (val.Error == null)
{
var result = (IDictionary<string, object>)val.Result;
Dispatcher.BeginInvoke(() => InfoBox.ItemsSource = result);
}
else
{
// TODO: Need to let the user know there was an error
//failedLogin();
}
});
So how do I just get the name?
regards
Even
I'm JeongSeop Kim. Korean.
You can access infomation by using Dispatcher.BeginInvoke() func.
for example.
Dispatcher.BeginInvoke(() => firstNameTxtBlock.Text = result["first_name"].ToString());
Maybe you can see:)
Good Lock!