Hi Rahul,
Following is the example for Username-password authentication using Oauth.
String endpoint=’https://login.salesforce.com/services/oauth2/token’;
String username = ‘USER NAME HERE of X org’;
String password = ‘PASSWORD without security token’;
String ClientId= ‘connected app on Z org’;
String ClientSecret = ‘xxxxxx’;
Httprequest req = new HttpRequest();
req.setMethod(‘POST’);
req.setHeader(‘Content-Type’,’application/x-www-form-urlencoded’);
req.setBody(‘grant_type=password’ +
‘&client_id=’ + ClientId +
‘&client_secret=’ + ClientSecret +
‘&username=’ + username +
‘&password=’ + password
);
req.setEndpoint(endpoint);
Http http = new Http();
HttpResponse res;
try {
res = http.send(req);
system.debug(‘body:’+res.getBody());
}catch(system.CalloutException e){
system.debug(‘error’+e);
}
Hope this help you.!