Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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());
- }
- }
- public static void sendNotification(String name, String city) {
- HttpRequest req = new HttpRequest();
- HttpResponse res = new HttpResponse();
- Http http = new Http();
- req.setEndpoint('http://my-end-point.com/newCustomer');
- req.setMethod('POST');
- req.setBody('name='+EncodingUtil.urlEncode(name, 'UTF-8')+'&city='+EncodingUtil.urlEncode(city, 'UTF-8'));
- req.setCompressed(true); // otherwise we hit a limit of 32000
- try {
- res = http.send(req);
- } catch(System.CalloutException e) {
- System.debug('Callout error: '+ e);
- System.debug(res.toString());
- }
- }
- // run WebServiceCallout.testMe(); from Execute Anonymous to test
- public static testMethod void testMe() {
- WebServiceCallout.sendNotification('My Test Customer','My City');
- }
- HttpRequest req = new HttpRequest();
- HttpResponse res = new HttpResponse();
- Http http = new Http();
- req.setEndpoint('https://www.mysite.com/myendpoint');
- req.setMethod('POST');
- //these parts of the POST you may want to customize
- req.setCompressed(false);
- req.setBody('key1=value1&key2=value2');
- req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
- try {
- res = http.send(req);
- } catch(System.CalloutException e) {
- System.debug('Callout error: '+ e);
- }
- System.debug(res.getBody());
- HttpRequest req = new HttpRequest();
- HttpResponse res = new HttpResponse();
- Http http = new Http();
- req.setEndpoint('callout:My_Named_Credential/some_path');
- req.setMethod('POST');
- req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
- req.setBody('key1=value1&key2=value2');
- try {
- res = http.send(req);
- if (res.getStatusCode() == 200) {
- System.debug('Success!');
- } else {
- System.debug('HTTP error: ' + res.getStatusCode());
- }
- System.debug(res.getBody());
- } catch(System.CalloutException e) {
- System.debug('Callout error: '+ e);
- }
Add Comment
Please, Sign In to add comment