NetUtil.jsm

  • Revision slug: JavaScript_code_modules/NetUtil.jsm
  • Revision title: NetUtil.jsm
  • Revision id: 45669
  • Created:
  • Creator: Sheppy
  • Is current revision? No
  • Comment 94 words added, 12 words removed

Revision Content

{{ gecko_minversion_header("1.9.2") }}

The NetUtil.jsm JavaScript code module provides easy-to-use APIs for performing common network related tasks.

To use these utilities, you first need to import the code module into your JavaScript scope:

Components.utils.import("resource://gre/modules/NetUtil.jsm");

Once you've imported the module, you can then use its methods.

Method overview

{{ interface("nsIAsyncStreamCopier") }} asyncCopy({{ interface("nsIInputStream") }} aSource, {{ interface("nsIOutputStream") }} aSink, [optional] aCallback)
void asyncFetch(aSource, [optional] aCallback)
{{ interface("nsIChannel") }} newChannel(aWhatToLoad, [optional] aOriginCharset, [optional] {{ interface("nsIURI") }} aBaseURI)
{{ interface("nsIURI") }} newURI(aTarget, [optional] aOriginCharset, [optional] {{ interface("nsIURI") }} aBaseURI)

Attributes

Attribute Type Description
ioService {{ interface("nsIIOService") }} Returns a reference to {{ interface("nsIIOService") }}. {{ gecko_minversion_inline("1.9.3") }}

Methods

asyncCopy

The asyncCopy() method performs a simple asynchronous copy of data from a source input stream to a destination input stream. Both streams are automatically closed when the copy operation is completed.

nsIAsyncStreamCopier asyncCopy(
  aSource,
  aSink,
  aCallback
); 
Parameters
aSource
The input stream from which to read the source data. This must be an {{ interface("nsIInputStream") }} based object.
aSink
The output stream to which to copy the data. This must be an {{ interface("nsIOutputStream") }} based object.
aCallback
An optional function that will be called when the copy operation is completed. The callback receives a single parameter: the nsresult status code for the copy operation.
Return value

Returns the {{ interface("nsIAsyncStreamCopier") }} object that is handling the copy.

Exceptions thrown

This method throws an exception with the message "Must have a source and a sink" if either aSource or aSink is null.

Example

This example writes a string to a file; it comes from the test suite for the NetUtil module.

var file = Cc["@mozilla.org/file/directory_service;1"].
           getService(Ci.nsIProperties).
           get("TmpD", Ci.nsIFile);
file.append("test-file.tmp");
file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0666);

// Then, we need an output stream to our output file.
var ostream = Cc["@mozilla.org/network/file-output-stream;1"].
              createInstance(Ci.nsIFileOutputStream);
ostream.init(file, -1, -1, 0);

// Finally, we need an input stream to take data from.
const TEST_DATA = "this is a test string";
let istream = Cc["@mozilla.org/io/string-input-stream;1"].
              createInstance(Ci.nsIStringInputStream);
istream.setData(TEST_DATA, TEST_DATA.length);

NetUtil.asyncCopy(istream, ostream, function(aResult) {
  if (!Components.isSuccessCode(aResult)) {
    // an error occurred!
  }
})

asyncFetch

The asyncFetch() method opens an input source, asynchronously, and gives an {{ interface("nsIInputStream") }} containing the data obtained to the callback provided. The callback may then consume data from the input stream passed to the callback.

{{ gecko_minversion_note("1.9.3", "Prior to Gecko 1.9.3, the input source was required to be specified as an nsIChannel.") }}

asyncFetch(
  aSource,
  aCallback
); 
Parameters
aSource
The source to open asynchronously. This may be specified as an {{ interface("nsIURI") }}, {{ interface("nsIFile") }}, {{ interface("nsIChannel") }}, or as a string specifying the URL to open.
aCallback
A function that will be called when the open operation is completed. The callback receives two parameters: the input stream containing the data (implementing {{ interface("nsIInputStream") }}) and the nsresult status code for the open operation.
Exceptions thrown

This method throws an exception with the message "Must have a source and a callback" if either aSource or aCallback is null.

Example

This example shows the basic code consumers would need to implement to be correct.

NetUtil.asyncFetch(channel, function(aInputStream, aResult) {
  // Check that we had success.
  if (!Components.isSuccessCode(aResult)) {
    // Handle error
    return;
  }

  // Consume the input stream.
});

{{ method_gecko_minversion("newChannel", "1.9.3") }}

Creates a new channel for the specified URI string, {{ interface("nsIURI") }}, or {{ interface("nsIFile") }}.

nsIChannel newChannel(
  aWhatToLoad,
  [optional] aOriginCharset,
  [optional] aBaseURI
); 
Parameters
aWhatToLoad
A string specifying a URI, or an {{ interface("nsIURI") }} or {{ interface("nsIFile") }} object. The returned method will allow access to the specified data.
aOriginCharset
The optional character set to use when interpreting aWhatToLoad as a string; this is ignored if aWhatToLoad is not a string. Defaults to UTF-8 if not provided.
aBaseURI
The base URI for the spec, specified as an {{ interface("nsIURI") }}. Only used if aWhatToLoad is a string.
Return value

An {{ interface("nsIChannel") }} allowing access to the specified data source.

newURI

The newURI() method creates a new {{ interface("nsIURI") }}. This method wraps the {{ ifandmethod("nsIIOService", "newURI") }}.

{{ gecko_callout_heading("1.9.3") }}

Starting in Gecko 1.9.3, this method supports specifying an {{ interface("nsIFile") }} as the target of the URI. In previous versions of Gecko, you must use a string to specify the URI.

nsIURI newURI(
  aTarget,
  [optinoal] aOriginCharset,
  [optional] aBaseURI
); 
Parameters
aTarget
Specifies the target of the URI as either a URI string or (starting in {{ Gecko("1.9.3") }}) as an {{ interface("nsIFile") }}.
aOriginCharset
The optional character set for the URI. Defaults to UTF-8 if not provided.
aBaseURI
The base URI for the spec, specified as an {{ interface("nsIURI") }}.
Return value

Returns the {{ interface("nsIURI") }} object representing the specified target.

Exceptions thrown

This method throws an exception with the message "Must have a non-null string spec or nsIFile object" and result code NS_ERROR_INVALID_ARG if aSpec is null.

See also

Revision Source

<p>{{ gecko_minversion_header("1.9.2") }}</p>
<p>The <code>NetUtil.jsm</code> JavaScript code module provides easy-to-use APIs for performing common network related tasks.</p>
<p>To use these utilities, you first need to import the code module into your JavaScript scope:</p>
<pre class="eval"><span class="nowiki">Components.utils.import("</span><span class="nowiki">resource://gre/modules/NetUtil.jsm</span><span class="nowiki">");</span>
</pre>
<p>Once you've imported the module, you can then use its methods.</p>
<h2 name="Method_overview">Method overview</h2>
<table class="standard-table"> <tbody> <tr> <td><code>{{ interface("nsIAsyncStreamCopier") }} asyncCopy({{ interface("nsIInputStream") }} aSource, {{ interface("nsIOutputStream") }} aSink, [optional] aCallback)</code></td> </tr> <tr> <td><code>void asyncFetch(aSource, [optional] aCallback)</code></td> </tr> <tr> <td><code>{{ interface("nsIChannel") }} newChannel(aWhatToLoad, [optional] aOriginCharset, [optional] {{ interface("nsIURI") }} aBaseURI)</code></td> </tr> <tr> <td><code>{{ interface("nsIURI") }} newURI(aTarget, [optional] aOriginCharset, [optional] {{ interface("nsIURI") }} aBaseURI)</code></td> </tr> </tbody>
</table>
<h2>Attributes</h2>
<table class="standard-table"> <tbody> <tr> <td class="header">Attribute</td> <td class="header">Type</td> <td class="header">Description</td> </tr> <tr> <td><code>ioService</code></td> <td>{{ interface("nsIIOService") }}</td> <td>Returns a reference to {{ interface("nsIIOService") }}. {{ gecko_minversion_inline("1.9.3") }}</td> </tr> </tbody>
</table>
<h2>Methods</h2>
<h3>asyncCopy</h3>
<p>The <code>asyncCopy()</code> method performs a simple asynchronous copy of data from a source input stream to a destination input stream. Both streams are automatically closed when the copy operation is completed.</p>
<pre>nsIAsyncStreamCopier asyncCopy(
  aSource,
  aSink,
  aCallback
); 
</pre>
<h6>Parameters</h6>
<dl> <dt><code>aSource</code></dt> <dd>The input stream from which to read the source data. This must be an {{ interface("nsIInputStream") }} based object.</dd> <dt><code>aSink</code></dt> <dd>The output stream to which to copy the data. This must be an {{ interface("nsIOutputStream") }} based object.</dd> <dt><code>aCallback</code></dt> <dd>An optional function that will be called when the copy operation is completed. The callback receives a single parameter: the <code>nsresult</code> status code for the copy operation.</dd>
</dl>
<h6>Return value</h6>
<p>Returns the {{ interface("nsIAsyncStreamCopier") }} object that is handling the copy.</p>
<h6>Exceptions thrown</h6>
<p>This method throws an exception with the message "Must have a source and a sink" if either <code>aSource</code> or <code>aSink</code> is null.</p>
<h4>Example</h4>
<p>This example writes a string to a file; it comes from the test suite for the NetUtil module.</p>
<pre class="brush: js">var file = Cc["@mozilla.org/file/directory_service;1"].
           getService(Ci.nsIProperties).
           get("TmpD", Ci.nsIFile);
file.append("test-file.tmp");
file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0666);

// Then, we need an output stream to our output file.
var ostream = Cc["@mozilla.org/network/file-output-stream;1"].
              createInstance(Ci.nsIFileOutputStream);
ostream.init(file, -1, -1, 0);

// Finally, we need an input stream to take data from.
const TEST_DATA = "this is a test string";
let istream = Cc["@mozilla.org/io/string-input-stream;1"].
              createInstance(Ci.nsIStringInputStream);
istream.setData(TEST_DATA, TEST_DATA.length);

NetUtil.asyncCopy(istream, ostream, function(aResult) {
  if (!Components.isSuccessCode(aResult)) {
    // an error occurred!
  }
})
</pre>
<h3>asyncFetch</h3>
<p>The <code>asyncFetch()</code> method opens an input source, asynchronously, and gives an {{ interface("nsIInputStream") }} containing the data obtained to the callback provided. The callback may then consume data from the input stream passed to the callback.</p>
<p>{{ gecko_minversion_note("1.9.3", "Prior to Gecko 1.9.3, the input source was required to be specified as an <code>nsIChannel</code>.") }}</p>
<pre>asyncFetch(
  aSource,
  aCallback
); 
</pre>
<h6>Parameters</h6>
<dl> <dt><code>aSource</code></dt> <dd>The source to open asynchronously. This may be specified as an {{ interface("nsIURI") }}, {{ interface("nsIFile") }}, {{ interface("nsIChannel") }}, or as a string specifying the URL to open.</dd> <dt><code>aCallback</code></dt> <dd>A function that will be called when the open operation is completed. The callback receives two parameters: the input stream containing the data (implementing {{ interface("nsIInputStream") }}) and the <code>nsresult</code> status code for the open operation.</dd>
</dl>
<h6>Exceptions thrown</h6>
<p>This method throws an exception with the message "Must have a source and a callback" if either <code>aSource</code> or <code>aCallback</code> is null.</p>
<h4>Example</h4>
<p>This example shows the basic code consumers would need to implement to be correct.</p>
<pre class="brush: js">NetUtil.asyncFetch(channel, function(aInputStream, aResult) {
  // Check that we had success.
  if (!Components.isSuccessCode(aResult)) {
    // Handle error
    return;
  }

  // Consume the input stream.
});</pre>
<p>{{ method_gecko_minversion("newChannel", "1.9.3") }}</p>
<p>Creates a new channel for the specified URI string, {{ interface("nsIURI") }}, or {{ interface("nsIFile") }}.</p>
<pre>nsIChannel newChannel(
  aWhatToLoad,
  [optional] aOriginCharset,
  [optional] aBaseURI
); 
</pre>
<h6>Parameters</h6>
<dl> <dt><code>aWhatToLoad</code></dt> <dd>A string specifying a URI, or an {{ interface("nsIURI") }} or {{ interface("nsIFile") }} object. The returned method will allow access to the specified data.</dd> <dt><code>aOriginCharset</code></dt> <dd>The optional character set to use when interpreting <code>aWhatToLoad</code> as a string; this is ignored if <code>aWhatToLoad</code> is not a string. Defaults to UTF-8 if not provided.</dd> <dt><code>aBaseURI</code></dt> <dd>The base URI for the spec, specified as an {{ interface("nsIURI") }}. Only used if <code>aWhatToLoad</code> is a string.</dd> <h6>Return value</h6> <p>An {{ interface("nsIChannel") }} allowing access to the specified data source.</p>
</dl>
<h3>newURI</h3>
<p>The <code>newURI()</code> method creates a new {{ interface("nsIURI") }}. This method wraps the {{ ifandmethod("nsIIOService", "newURI") }}.</p>
<div class="geckoVersionNote">
<p>{{ gecko_callout_heading("1.9.3") }}</p>
<p>Starting in Gecko 1.9.3, this method supports specifying an {{ interface("nsIFile") }} as the target of the URI. In previous versions of Gecko, you must use a string to specify the URI.</p>
</div>
<pre>nsIURI newURI(
  aTarget,
  [optinoal] aOriginCharset,
  [optional] aBaseURI
); 
</pre>
<h6>Parameters</h6>
<dl> <dt><code>aTarget</code></dt> <dd>Specifies the target of the URI as either a URI string or (starting in {{ Gecko("1.9.3") }}) as an {{ interface("nsIFile") }}.</dd> <dt><code>aOriginCharset</code></dt> <dd>The optional character set for the URI. Defaults to UTF-8 if not provided.</dd> <dt><code>aBaseURI</code></dt> <dd>The base URI for the spec, specified as an {{ interface("nsIURI") }}.</dd>
</dl>
<h6>Return value</h6>
<p>Returns the {{ interface("nsIURI") }} object representing the specified target.</p>
<h6>Exceptions thrown</h6>
<p>This method throws an exception with the message "Must have a non-null string spec or nsIFile object" and result code <code>NS_ERROR_INVALID_ARG</code> if <code>aSpec</code> is null.</p>
<h2>See also</h2>
<ul> <li><a class="internal" href="/en/JavaScript_code_modules/Using_JavaScript_code_modules" title="en/JavaScript code modules/Using JavaScript code modules">Using JavaScript code modules</a></li> <li><a class="internal" href="/en/JavaScript_code_modules" title="en/JavaScript code modules">JavaScript code modules</a></li> <li><a class="internal" href="/en/Components.utils.import" title="en/Components.utils.import"><code>Components.utils.import</code></a></li>
</ul>
Revert to this revision