• Skip to content
  • Skip to link menu
KDE 4.1 API Reference
  • KDE API Reference
  • kdelibs
  • Sitemap
  • Contact Us
 

KDECore

KUrl Class Reference

#include <KUrl>

Inheritance diagram for KUrl:

Inheritance graph
[legend]

List of all members.


Detailed Description

Represents and parses a URL.

A prototypical URL looks like:

   protocol://user:password\@hostname:port/path/to/file.ext#reference

KUrl handles escaping of URLs. This means that the specification of a full URL will differ from the corresponding string that would specify a local file or directory in file-operations like fopen. This is because an URL doesn't allow certain characters and escapes them. (e.g. '#'->"%23", space->"%20") (In a URL the hash-character '#' is used to specify a "reference", i.e. the position within a document).

The constructor KUrl(const QString&) expects a string properly escaped, or at least non-ambiguous. If you have the absolute path you should use KUrl::fromPath(const QString&).

     KUrl kurl = KUrl::fromPath("/bar/#foo#");
     QString url = kurl.url();    // -> "file:///bar/%23foo%23"

If you have the URL of a local file or directory and need the absolute path, you would use path().

    KUrl url( "file:///bar/%23foo%23" );
    ...
    if ( url.isLocalFile() )
       QString path = url.path();       // -> "/bar/#foo#"

This must also be considered when you have separated directory and file strings and need to put them together. While you can simply concatenate normal path strings, you must take care if the directory-part is already an escaped URL. (This might be needed if the user specifies a relative path, and your program supplies the rest from elsewhere.)

Wrong:

    QString dirUrl = "file:///bar/";
    QString fileName = "#foo#";
    QString invalidURL = dirUrl + fileName;   // -> "file:///bar/#foo#" won't behave like you would expect.
Instead you should use addPath(): Right:
    KUrl url( "file:///bar/" );
    QString fileName = "#foo#";
    url.addPath( fileName );
    QString validURL = url.url();    // -> "file:///bar/%23foo%23"

Also consider that some URLs contain the password, but this shouldn't be visible. Your program should use prettyUrl() every time it displays a URL, whether in the GUI or in debug output or...

    KUrl url( "ftp://name:password@ftp.faraway.org/bar/%23foo%23");
    QString visibleURL = url.prettyUrl(); // -> "ftp://name@ftp.faraway.org/bar/%23foo%23"
Note that prettyUrl() doesn't change the character escapes (like "%23"). Otherwise the URL would be invalid and the user wouldn't be able to use it in another context.

Definition at line 111 of file kurl.h.


Public Types

enum  AdjustPathOption { RemoveTrailingSlash, LeaveTrailingSlash, AddTrailingSlash }
enum  CleanPathOption { SimplifyDirSeparators = 0x00, KeepDirSeparators = 0x01 }
enum  DirectoryOption { ObeyTrailingSlash = 0x02, AppendTrailingSlash = 0x04, IgnoreTrailingSlash = 0x01 }
enum  EncodedPathAndQueryOption { PermitEmptyPath = 0x00, AvoidEmptyPath = 0x01 }
enum  EqualsOption { CompareWithoutTrailingSlash = 0x01, CompareWithoutFragment = 0x02 }
typedef QMap< QString, QString > MetaDataMap
enum  MimeDataFlags { DefaultMimeDataFlags = 0, NoTextExport = 1 }
enum  QueryItemsOption { CaseInsensitiveKeys = 1 }

Public Member Functions

void addPath (const QString &txt)
void addQueryItem (const QString &_item, const QString &_value)
void adjustPath (AdjustPathOption trailing)
bool cd (const QString &_dir)
void cleanPath (const CleanPathOption &options=SimplifyDirSeparators)
bool cmp (const KUrl &u, bool ignore_trailing=false) const
QString directory (const DirectoryOptions &options=IgnoreTrailingSlash) const
QString encodedHtmlRef () const
QString encodedPathAndQuery (AdjustPathOption trailing=LeaveTrailingSlash, const EncodedPathAndQueryOptions &options=PermitEmptyPath) const
bool equals (const KUrl &u, const EqualsOptions &options=0) const
QString fileEncoding () const
QString fileName (const DirectoryOptions &options=IgnoreTrailingSlash) const
bool hasHost () const
bool hasHTMLRef () const
bool hasPass () const
bool hasPath () const
bool hasRef () const
bool hasSubUrl () const
bool hasUser () const
QString htmlRef () const
bool isLocalFile () const
bool isParentOf (const KUrl &u) const
 KUrl (const KUrl &_baseurl, const QString &_rel_url)
 KUrl (const QUrl &u)
 KUrl (const KUrl &u)
 KUrl (const QByteArray &urlOrPath)
 KUrl (const char *urlOrPath)
 KUrl (const QString &urlOrPath)
 KUrl ()
 operator QVariant () const
bool operator!= (const QString &_u) const
bool operator!= (const KUrl &_u) const
KUrl & operator= (const QString &_url)
KUrl & operator= (const QByteArray &_url)
KUrl & operator= (const char *_url)
KUrl & operator= (const KUrl &_u)
bool operator== (const QString &_u) const
bool operator== (const KUrl &_u) const
QString pass () const
QString path (AdjustPathOption trailing=LeaveTrailingSlash) const
QString pathOrUrl () const
void populateMimeData (QMimeData *mimeData, const MetaDataMap &metaData=MetaDataMap(), MimeDataFlags flags=DefaultMimeDataFlags) const
QString prettyUrl (AdjustPathOption trailing=LeaveTrailingSlash) const
QString protocol () const
QString query () const
QString queryItem (const QString &item) const
QMap< QString, QString > queryItems (const QueryItemsOptions &options=0) const
QString ref () const
void setDirectory (const QString &dir)
void setEncodedPathAndQuery (const QString &_txt)
void setFileEncoding (const QString &encoding)
void setFileName (const QString &_txt)
void setHTMLRef (const QString &_ref)
void setPass (const QString &pass)
void setPath (const QString &path)
void setProtocol (const QString &proto)
void setQuery (const QString &query)
void setRef (const QString &fragment)
void setUser (const QString &user)
QString toLocalFile (AdjustPathOption trailing=LeaveTrailingSlash) const
QString toMimeDataString () const
KUrl upUrl () const
QString url (AdjustPathOption trailing=LeaveTrailingSlash) const
QString user () const
 ~KUrl ()

Static Public Member Functions

static QString decode_string (const QString &str)
static QString encode_string (const QString &str)
static QString encode_string_no_slash (const QString &str)
static KUrl fromMimeDataByteArray (const QByteArray &str)
static KUrl fromPath (const QString &text)
static KUrl fromPathOrUrl (const QString &text)
static bool isRelativeUrl (const QString &_url)
static KUrl join (const List &_list)
static QString relativePath (const QString &base_dir, const QString &path, bool *isParent=0)
static QString relativeUrl (const KUrl &base_url, const KUrl &url)
static List split (const KUrl &_url)
static List split (const QString &_url)

Related Functions

(Note that these are not member functions.)

bool urlcmp (const QString &_url1, const QString &_url2, const KUrl::EqualsOptions &options)
bool urlcmp (const QString &_url1, const QString &_url2)

Classes

class  List
 KUrl::List is a QList that contains KUrls with a few convenience methods. More...

Member Typedef Documentation

typedef QMap<QString, QString> KUrl::MetaDataMap

Definition at line 114 of file kurl.h.


Member Enumeration Documentation

enum KUrl::AdjustPathOption

Options to be used in adjustPath.

Enumerator:
RemoveTrailingSlash  strips any trailing '/'
LeaveTrailingSlash  Do not change the path.
AddTrailingSlash  adds a trailing '/' if there is none yet

Definition at line 320 of file kurl.h.

enum KUrl::CleanPathOption

Options to be used in cleanPath.

Enumerator:
SimplifyDirSeparators  if set, occurrences of consecutive directory separators (e.g.

/foo//bar) are cleaned up as well. (set by default)

KeepDirSeparators  The opposite of SimplifyDirSeparators.

Definition at line 366 of file kurl.h.

enum KUrl::DirectoryOption

option to be used in fileName and directory

Enumerator:
ObeyTrailingSlash  This tells whether a trailing '/' should be ignored.

If the flag is not set, for both file:///hallo/torben/ and file:///hallo/torben the fileName is "torben" and the path is "hallo"

If the flag is set, then everything behind the last '/'is considered to be the filename. So "hallo/torben" will be the path and the filename will be empty.

AppendTrailingSlash  tells whether the returned result should end with '/' or not.

If the flag is set, '/' is added to the end of the path

If the path is empty or just "/" then this flag has no effect.

This option should only be used in directory(), it has no effect in fileName()

IgnoreTrailingSlash  Opposite of ObeyTrailingSlash (default).

Definition at line 632 of file kurl.h.

enum KUrl::EncodedPathAndQueryOption

Option to be used in encodedPathAndQuery.

Enumerator:
PermitEmptyPath  Permit empty path (default).
AvoidEmptyPath  If set to true then an empty path is substituted by "/" (this is the opposite of PermitEmptyPath).

Definition at line 427 of file kurl.h.

enum KUrl::EqualsOption

flags to be used in url compartators function like equal, or urlcmp

Enumerator:
CompareWithoutTrailingSlash  ignore trailing '/' characters
CompareWithoutFragment  disables comparison of HTML-style references.

Definition at line 793 of file kurl.h.

enum KUrl::MimeDataFlags

Enumerator:
DefaultMimeDataFlags 
NoTextExport 

Definition at line 115 of file kurl.h.

enum KUrl::QueryItemsOption

Options for queryItems.

Currently, only one option is defined:

Parameters:
CaseInsensitiveKeys normalize query keys to lowercase.
Enumerator:
CaseInsensitiveKeys 

Definition at line 571 of file kurl.h.


Constructor & Destructor Documentation

KUrl::KUrl (  ) 

Constructs an empty URL.

Definition at line 337 of file kurl.cpp.

KUrl::~KUrl (  ) 

Destructs the KUrl object.

Definition at line 342 of file kurl.cpp.

KUrl::KUrl ( const QString &  urlOrPath  ) 

Usual constructor, to construct from a string.

Parameters:
urlOrPath An encoded URL or a path.

Definition at line 347 of file kurl.cpp.

KUrl::KUrl ( const char *  urlOrPath  )  [explicit]

Constructor taking a char * urlOrPath, which is an _encoded_ representation of the URL, exactly like the usual constructor.

This is useful when the URL, in its encoded form, is strictly ascii.

Parameters:
urlOrPath An encoded URL, or a path.

Definition at line 375 of file kurl.cpp.

KUrl::KUrl ( const QByteArray &  urlOrPath  )  [explicit]

Constructor taking a QByteArray urlOrPath, which is an _encoded_ representation of the URL, exactly like the usual constructor.

This is useful when the URL, in its encoded form, is strictly ascii.

Parameters:
urlOrPath An encoded URL, or a path.

Definition at line 409 of file kurl.cpp.

KUrl::KUrl ( const KUrl &  u  ) 

Copy constructor.

Parameters:
u the KUrl to copy

Definition at line 430 of file kurl.cpp.

KUrl::KUrl ( const QUrl &  u  ) 

Converts from a QUrl.

Parameters:
u the QUrl

Definition at line 438 of file kurl.cpp.

KUrl::KUrl ( const KUrl &  _baseurl,
const QString &  _rel_url 
)

Constructor allowing relative URLs.

Parameters:
_baseurl The base url.
_rel_url A relative or absolute URL. If this is an absolute URL then _baseurl will be ignored. If this is a relative URL it will be combined with _baseurl. Note that _rel_url should be encoded too, in any case. So do NOT pass a path here (use setPath or addPath instead).

Definition at line 446 of file kurl.cpp.


Member Function Documentation

void KUrl::addPath ( const QString &  txt  ) 

Adds to the current path.

Assumes that the current path is a directory. _txt is appended to the current path. The function adds '/' if needed while concatenating. This means it does not matter whether the current path has a trailing '/' or not. If there is none, it becomes appended. If _txt has a leading '/' then this one is stripped.

Parameters:
txt The text to add. It is considered to be decoded.

Reimplemented from QUrl.

Definition at line 1247 of file kurl.cpp.

void KUrl::addQueryItem ( const QString &  _item,
const QString &  _value 
)

Add an additional query item.

To replace an existing query item, the item should first be removed with removeQueryItem()

Parameters:
_item Name of item to add
_value Value of item to add

Reimplemented from QUrl.

Definition at line 1758 of file kurl.cpp.

void KUrl::adjustPath ( AdjustPathOption  trailing  ) 

Add or remove a trailing slash to/from the path.

If the URL has no path, then no '/' is added anyway. And on the other side: If the path is "/", then this character won't be stripped. Reason: "ftp://weis\@host" means something completely different than "ftp://weis\@host/". So adding or stripping the '/' would really alter the URL, while "ftp://host/path" and "ftp://host/path/" mean the same directory.

Parameters:
trailing RemoveTrailingSlash strips any trailing '/' and AddTrailingSlash adds a trailing '/' if there is none yet

Definition at line 747 of file kurl.cpp.

bool KUrl::cd ( const QString &  _dir  ) 

Changes the directory by descending into the given directory.

It is assumed the current URL represents a directory. If dir starts with a "/" the current URL will be "protocol://host/dir" otherwise _dir will be appended to the path. _dir can be ".." This function won't strip protocols. That means that when you are in file:///dir/dir2/my.tgz#tar:/ and you do cd("..") you will still be in file:///dir/dir2/my.tgz#tar:/

Parameters:
_dir the directory to change to
Returns:
true if successful

Definition at line 1317 of file kurl.cpp.

void KUrl::cleanPath ( const CleanPathOption &  options = SimplifyDirSeparators  ) 

Resolves "." and ".." components in path.

Some servers seem not to like the removal of extra '/' even though it is against the specification in RFC 2396.

Parameters:
options use KeepDirSeparators if you don't want to remove consecutive occurrences of directory separator

Definition at line 704 of file kurl.cpp.

bool KUrl::cmp ( const KUrl &  u,
bool  ignore_trailing = false 
) const

The same as equals(), just with a less obvious name.

Compares this url with u.

Parameters:
u the URL to compare this one with.
ignore_trailing set to true to ignore trailing '/' characters.
Returns:
true if both urls are the same
See also:
operator==. This function should be used if you want to ignore trailing '/' characters.
Deprecated:
Use equals() instead.

Definition at line 564 of file kurl.cpp.

static QString KUrl::decode_string ( const QString &  str  )  [inline, static]

Decode -style encoding and convert from local encoding to unicode.

Reverse of encode_string()

Parameters:
str String to decode (can be QString()).
Deprecated:
use QUrl::fromPercentEncoding(encodedURL) instead, but note that it takes a QByteArray and not a QString. Which makes sense since everything is 7 bit (ascii) when being percent-encoded.

Definition at line 952 of file kurl.h.

QString KUrl::directory ( const DirectoryOptions &  options = IgnoreTrailingSlash  )  const

Returns the directory of the path.

Parameters:
options a set of DirectoryOption flags
Returns:
The directory part of the current path. Everything between the last and the second last '/' is returned. For example file:///hallo/torben/ would return "/hallo/torben/" while file:///hallo/torben would return "hallo/". The returned string is decoded. QString() is returned when there is no path.

Definition at line 1283 of file kurl.cpp.

static QString KUrl::encode_string ( const QString &  str  )  [inline, static]

Convert unicoded string to local encoding and use -style encoding for all common delimiters / non-ascii characters.

Parameters:
str String to encode (can be QString()).
Returns:
the encoded string
Deprecated:
use QUrl::toPercentEncoding instead, but note that it returns a QByteArray and not a QString. Which makes sense since everything is 7 bit (ascii) after being percent-encoded.

Definition at line 923 of file kurl.h.

static QString KUrl::encode_string_no_slash ( const QString &  str  )  [inline, static]

Convert unicoded string to local encoding and use -style encoding for all common delimiters / non-ascii characters as well as the slash '/'.

Parameters:
str String to encode
Deprecated:
use QUrl::toPercentEncoding(str,"/") instead, but note that it returns a QByteArray and not a QString. Which makes sense since everything is 7 bit (ascii) after being percent-encoded.

Definition at line 938 of file kurl.h.

QString KUrl::encodedHtmlRef (  )  const

Returns the HTML reference (the part of the URL after "#") in encoded form.

Returns:
The HTML-style reference in its original form.

Definition at line 1421 of file kurl.cpp.

QString KUrl::encodedPathAndQuery ( AdjustPathOption  trailing = LeaveTrailingSlash,
const EncodedPathAndQueryOptions &  options = PermitEmptyPath 
) const

Returns the encoded path and the query.

Parameters:
trailing add or remove a trailing '/', see adjustPath
options a set of flags from EncodedPathAndQueryOption
Returns:
The concatenation of the encoded path , '?' and the encoded query.

Definition at line 761 of file kurl.cpp.

bool KUrl::equals ( const KUrl &  u,
const EqualsOptions &  options = 0 
) const

Compares this url with u.

Parameters:
u the URL to compare this one with.
options a set of EqualsOption flags
Returns:
true if both urls are the same
See also:
operator==. This function should be used if you want to ignore trailing '/' characters.

Definition at line 569 of file kurl.cpp.

QString KUrl::fileEncoding (  )  const

Returns encoding information from url, the content of the "charset" parameter.

Returns:
An encoding suitable for QTextCodec::codecForName() or QString() if not encoding was specified.

Definition at line 896 of file kurl.cpp.

QString KUrl::fileName ( const DirectoryOptions &  options = IgnoreTrailingSlash  )  const

Returns the filename of the path.

Parameters:
options a set of DirectoryOption flags. (StripTrailingSlashFromResult has no effect)
Returns:
The filename of the current path. The returned string is decoded. Null if there is no file (and thus no path).

Definition at line 1186 of file kurl.cpp.

KUrl KUrl::fromMimeDataByteArray ( const QByteArray &  str  )  [static]

Creates a KUrl from a string, using the standard conventions for mime data (drag-n-drop or copy-n-paste).

Internally used by KUrl::List::fromMimeData, which is probably what you want to use instead.

Definition at line 1110 of file kurl.cpp.

KUrl KUrl::fromPath ( const QString &  text  )  [static]

Creates a KUrl object from a QString representing an absolute path.

KUrl url( somePath ) does the same, but this method is more explicit and avoids the path-or-url detection in the KUrl constructor.

Parameters:
text the path
Returns:
the new KUrl

Definition at line 652 of file kurl.cpp.

KUrl KUrl::fromPathOrUrl ( const QString &  text  )  [static]

Deprecated:
Since KDE4 you can pass both urls and paths to the KUrl constructors. Use KUrl(text) instead.

Definition at line 1572 of file kurl.cpp.

bool KUrl::hasHost (  )  const

Test to see if this URL has a hostname included in it.

Returns:
true if the URL has a host

Definition at line 642 of file kurl.cpp.

bool KUrl::hasHTMLRef (  )  const

Checks whether there is a HTML reference.

Returns:
true if the URL has an HTML-style reference.
See also:
htmlRef()

Definition at line 1447 of file kurl.cpp.

bool KUrl::hasPass (  )  const

Test to see if this URL has a password included in it.

Returns:
true if there is a non-empty password set

Definition at line 637 of file kurl.cpp.

bool KUrl::hasPath (  )  const

Test to see if this URL has a path is included in it.

Returns:
true if there is a path

Definition at line 647 of file kurl.cpp.

bool KUrl::hasRef (  )  const

Checks whether the URL has a reference part.

Returns:
true if the URL has a reference part. In a URL like http://www.kde.org/kdebase.tar#tar:/README it would return true, too.

Definition at line 1778 of file kurl.cpp.

bool KUrl::hasSubUrl (  )  const

Checks whether the URL has any sub URLs.

See split() for examples for sub URLs.

Returns:
true if the file has at least one sub URL.
See also:
split

Definition at line 959 of file kurl.cpp.

bool KUrl::hasUser (  )  const

Test to see if this URL has a user name included in it.

Returns:
true if the URL has an non-empty user name

Definition at line 622 of file kurl.cpp.

QString KUrl::htmlRef (  )  const

Returns the HTML reference (the part of the URL after "#").

Returns:
The HTML-style reference.
See also:
split

hasSubUrl

encodedHtmlRef

Definition at line 1410 of file kurl.cpp.

bool KUrl::isLocalFile (  )  const

Checks whether the file is local.

Returns:
true if the file is a plain local file and has no filter protocols attached to it.

Definition at line 862 of file kurl.cpp.

bool KUrl::isParentOf ( const KUrl &  u  )  const

Checks whether the given URL is parent of this URL.

For instance, ftp://host/dir/ is a parent of ftp://host/dir/subdir/subsubdir/.

Returns:
true if this url is a parent of u (or the same URL as u)

Definition at line 1799 of file kurl.cpp.

bool KUrl::isRelativeUrl ( const QString &  _url  )  [static]

Convenience function.

Returns whether '_url' is likely to be a "relative" URL instead of an "absolute" URL.

Parameters:
_url URL to examine
Returns:
true when the URL is likely to be "relative", false otherwise.

Reimplemented from QUrl.

Definition at line 158 of file kurl.cpp.

KUrl KUrl::join ( const List &  _list  )  [static]

Reverses split().

Only the first URL may have a reference. This reference is considered to be HTML-like and is appended at the end of the resulting joined URL.

Parameters:
_list the list to join
Returns:
the joined URL

Definition at line 1160 of file kurl.cpp.

KUrl::operator QVariant (  )  const

Converts this KUrl to a QVariant, this allows to use KUrl in QVariant() constructor.

Definition at line 559 of file kurl.cpp.

bool KUrl::operator!= ( const QString &  _u  )  const [inline]

Definition at line 769 of file kurl.h.

bool KUrl::operator!= ( const KUrl &  _u  )  const [inline]

Definition at line 768 of file kurl.h.

KUrl& KUrl::operator= ( const QString &  _url  )  [inline]

Reimplemented from QUrl.

Definition at line 764 of file kurl.h.

KUrl& KUrl::operator= ( const QByteArray &  _url  )  [inline]

Definition at line 763 of file kurl.h.

KUrl& KUrl::operator= ( const char *  _url  )  [inline]

Definition at line 762 of file kurl.h.

KUrl & KUrl::operator= ( const KUrl &  _u  ) 

Definition at line 542 of file kurl.cpp.

bool KUrl::operator== ( const QString &  _u  )  const

Definition at line 553 of file kurl.cpp.

bool KUrl::operator== ( const KUrl &  _u  )  const

Definition at line 548 of file kurl.cpp.

QString KUrl::pass (  )  const

Returns the decoded password (corresponding to user()) included in the URL.

Returns:
the password or QString() if it does not exist

Definition at line 627 of file kurl.cpp.

QString KUrl::path ( AdjustPathOption  trailing = LeaveTrailingSlash  )  const

Parameters:
trailing use to add or remove a trailing slash to/from the path.

see adjustPath

Returns:
The current decoded path. This does not include the query. Can be QString() if no path is set.

Definition at line 826 of file kurl.cpp.

QString KUrl::pathOrUrl (  )  const

Return the URL as a string, which will be either the URL (as prettyUrl would return) or, when the URL is a local file without query or ref, the path.

Use this method, to display URLs to the user. You can give the result of pathOrUrl back to the KUrl constructor, it accepts both paths and urls.

Returns:
the new KUrl

Definition at line 1069 of file kurl.cpp.

void KUrl::populateMimeData ( QMimeData *  mimeData,
const MetaDataMap &  metaData = MetaDataMap(),
MimeDataFlags  flags = DefaultMimeDataFlags 
) const

Adds URL data into the given QMimeData.

By default, populateMimeData also exports the URL as plain text, for e.g. dropping onto a text editor. But in some cases this might not be wanted, e.g. if adding other mime data which provides better plain text data.

WARNING: do not call this method multiple times, use KUrl::List::populateMimeData instead.

Parameters:
mimeData the QMimeData instance used to drag or copy this URL
metaData KIO metadata shipped in the mime data, which is used for instance to set a correct HTTP referrer (some websites require it for downloading e.g. an image)
flags set NoTextExport to prevent setting plain/text data into mimeData In such a case, setExportAsText( false ) should be called.

Definition at line 1770 of file kurl.cpp.

QString KUrl::prettyUrl ( AdjustPathOption  trailing = LeaveTrailingSlash  )  const

Returns the URL as string in human-friendly format.

Example:

 http://localhost:8080/test.cgi?test=hello world&name=fred
Parameters:
trailing use to add or remove a trailing slash to/from the path. see adjustPath.
Returns:
A human readable URL, with no non-necessary encodings/escaped characters. Password will not be shown.
See also:
url()

Definition at line 1000 of file kurl.cpp.