HttpRequest Class

Use the HttpRequest class to programmatically create HTTP requests like GET, POST, PUT, and DELETE.

Namespace

System

Usage

Use the XML classes or JSON classes to parse XML or JSON content in the body of a request created by HttpRequest.

Example

The following example illustrates how you can use an authorization header with a request, and handle the response:

public class AuthCallout {
 
   public void basicAuthCallout(){
     HttpRequest req = new HttpRequest();
     req.setEndpoint('http://www.yahoo.com');
     req.setMethod('GET');
     
     // Specify the required user name and password to access the endpoint
     // As well as the header and header information
 
     String username = 'myname';
     String password = 'mypwd';
  
     Blob headerValue = Blob.valueOf(username + ':' + password);
     String authorizationHeader = 'BASIC ' +
     EncodingUtil.base64Encode(headerValue);
     req.setHeader('Authorization', authorizationHeader);
   
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  
  
     Http http = new Http();
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());
   }
}
Note

Note

You can set the endpoint as a named credential instead of a URL. A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. Salesforce manages all the authentication for Apex callouts that specify a named credential as the callout endpoint, so that your code doesn’t have to. For an example, see setEndpoint(endpoint). To set up named credentials, see “Define a Named Credential” in the Salesforce Help.

Compression

If you need to compress the data you send, use setCompressed, as the following sample illustrates:

HttpRequest req = new HttpRequest();
req.setEndPoint('my_endpoint');
req.setCompressed(true);
req.setBody('some post body');

If a response comes back in compressed format, getBody automatically recognizes the format, uncompresses it, and returns the uncompressed value.

HttpRequest Constructors

The following are constructors for HttpRequest.

HttpRequest()

Creates a new instance of the HttpRequest class.

Signature

public HttpRequest()

HttpRequest Methods

The following are methods for HttpRequest. All are instance methods.

getBody()

Retrieves the body of this request.

Signature

public String getBody()

Return Value

Type: String

getBodyAsBlob()

Retrieves the body of this request as a Blob.

Signature

public Blob getBodyAsBlob()

Return Value

Type: Blob

getBodyDocument()

Retrieves the body of this request as a DOM document.

Signature

public Dom.Document getBodyDocument()

Return Value

Type: Dom.Document

Example

Use this method as a shortcut for:

String xml = httpRequest.getBody();
Dom.Document domDoc = new Dom.Document(xml);

getCompressed()

If true, the request body is compressed, false otherwise.

Signature

public Boolean getCompressed()

Return Value

Type: Boolean

getEndpoint()

Retrieves the URL for the endpoint of the external server for this request.

Signature

public String getEndpoint()

Return Value

Type: String

getHeader(key)

Retrieves the contents of the request header.

Signature

public String getHeader(String key)

Parameters

key
Type: String

Return Value

Type: String

getMethod()

Returns the type of method used by HttpRequest.

Signature

public String getMethod()

Return Value

Type: String

Usage

Examples of return values:

  • DELETE
  • GET
  • HEAD
  • POST
  • PUT
  • TRACE

setBody(body)

Sets the contents of the body for this request.

Signature

public Void setBody(String body)

Parameters

body
Type: String

Return Value

Type: Void

Usage

Limit: 6 MB for synchronous Apex or 12 MB for asynchronous Apex.

The HTTP request and response sizes count towards the total heap size.

setBodyAsBlob(body)

Sets the contents of the body for this request using a Blob.

Signature

public Void setBodyAsBlob(Blob body)

Parameters

body
Type: Blob

Return Value

Type: Void

Usage

Limit: 6 MB for synchronous Apex or 12 MB for asynchronous Apex.

The HTTP request and response sizes count towards the total heap size.

setBodyDocument(document)

Sets the contents of the body for this request. The contents represent a DOM document.

Signature

public Void setBodyDocument(Dom.Document document)

Parameters

document
Type: Dom.Document

Return Value

Type: Void

Usage

Limit: 6 MB for synchronous Apex or 12 MB for asynchronous Apex.

setClientCertificate(clientCert, password)

This method is deprecated. Use setClientCertificateName instead.

Signature

public Void setClientCertificate(String clientCert, String password)

Parameters

clientCert
Type: String
password
Type: String

Return Value

Type: Void

Usage

If the server requires a client certificate for authentication, set the client certificate PKCS12 key store and password.

setClientCertificateName(certDevName)

If the external service requires a client certificate for authentication, set the certificate name.

Signature

public Void setClientCertificateName(String certDevName)

Parameters

certDevName
Type: String

Return Value

Type: Void

setCompressed(flag)

If true, the data in the body is delivered to the endpoint in the gzip compressed format. If false, no compression format is used.

Signature

public Void setCompressed(Boolean flag)

Parameters

flag
Type: Boolean

Return Value

Type: Void

setEndpoint(endpoint)

Specifies the endpoint for this request.

Signature

public Void setEndpoint(String endpoint)

Parameters

endpoint
Type: String
Possible values for the endpoint:
  • Endpoint URL
    https://my_endpoint.example.com/some_path
  • Named credential URL, which contains the scheme callout, the name of the named credential, and, optionally, an appended path
    callout:My_Named_Credential/some_path

Return Value

Type: Void

Usage with Named Credentials

A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. Salesforce manages all the authentication for Apex callouts that specify a named credential as the callout endpoint, so that your code doesn’t have to. You can also skip remote site settings, which are otherwise required for Apex callouts to external sites.

By separating the endpoint URL and authentication from the Apex code, named credentials make callouts easier to maintain. For example, if an endpoint URL changes, you simply update the named credential. All callouts that reference the named credential then continue to work without any changes to the code. If you have multiple organizations, you can create a named credential with the same name in each organization. Each of these named credentials can have a different endpoint URL, for example, to accommodate differences in development and production environments. Because the code references only the named credential’s name, you can package and deploy the same Apex class in all your organizations without programmatically checking the environment.

If you add the Apex code to a managed package that doesn't contain the referenced named credential, include the namespace prefix when specifying the endpoint. For a subscriber organization that has no namespace set, use the . namespace prefix to reference the named credential. For example:
req.setEndpoint('callout:.__My_Named_Credential/some_path');

Example

In the following sample code, a named credential and an appended path specify the callout’s endpoint.
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:My_Named_Credential/some_path');
req.setMethod('GET');
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());
The referenced named credential specifies the endpoint URL and the authentication settings.Named credential detail pageYou can code the callout endpoint as the URL instead of the named credential, but your code then handles the authentication. Our example uses basic password authentication, but keep in mind that OAuth authentication is much more complex and best handled with named credentials.
HttpRequest req = new HttpRequest();
req.setEndpoint('https://my_endpoint.example.com/some_path');
req.setMethod('GET');

// Because we didn't set the endpoint as a named credential, 
// our code has to specify:
// - The required username and password to access the endpoint
// - The header and header information
 
String username = 'myname';
String password = 'mypwd';
  
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' +
EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);
   
// Create a new http object to send the request object
// A response object is generated as a result of the request  
  
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());

setHeader(key, value)

Sets the contents of the request header.

Signature

public Void setHeader(String key, String value)

Parameters

key
Type: String
value
Type: String

Return Value

Type: Void

Usage

Limit 100 KB.

setMethod(method)

Sets the type of method to be used for the HTTP request.

Signature

public Void setMethod(String method)

Parameters

method
Type: String
Possible values for the method type include:
  • DELETE
  • GET
  • HEAD
  • POST
  • PUT
  • TRACE

Return Value

Type: Void

Usage

You can also use this method to set any required options.

setTimeout(timeout)

Sets the timeout in milliseconds for the request.

Signature

public Void setTimeout(Integer timeout)

Parameters

timeout
Type: Integer

Return Value

Type: Void

Usage

The timeout can be any value between 1 and 120,000 milliseconds.

toString()

Returns a string containing the URL for the endpoint of the external server for this request and the method used, for example, Endpoint=http://YourServer, Method=POST

Signature

public String toString()

Return Value

Type: String