Salesforce test web service call - salesforce

Here is the code for a helper function
public class SalesforceHelper {
public static void waitCall(String timeout){
System_Settings__c lnpSetting = System_Settings__c.getValues('System Properties');
String endpoint=lnpSetting.Base_Endpoint_URL__c + 'salesforceHelper/wait?timeout=' + timeout;
system.debug('====endpoint======'+endpoint);
HttpRequest httpReq=new HttpRequest();
HttpResponse httpResp = new HttpResponse();
Http http = new Http();
httpReq.setMethod('GET');
httpReq.setEndpoint(endpoint);
String username=lnpSetting.Endpoint_Username__c;
String password=lnpSetting.Endpoint_Password__c;
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
httpReq.setHeader('Authorization', authorizationHeader);
httpReq.setHeader('content-type','application/json; charset=utf-8');
httpReq.setTimeout(120000);
try{
httpResp = http.send(httpReq);
System.debug('Wait response' + httpResp);
} catch (Exception e) {
system.debug(LoggingLevel.Error, 'Error HTTP response code = ' + httpResp.getStatusCode() + '; calling '+endpoint );
}
}
}
Basically this method just using HttpRequest and HttpResponse to call the endpoint URL, and the endpoint URL is web service, and it will just return 200 after the timeout that specified in the parameter.
Now the question is, I need to write a test case to cover this method, and I don't know how to write it.. I don't know how to mock the httpcallout properly, because this method doesn't return HttpResponse, and since the code is freeze right now, I cannot modified my class to make the test case work.
So any other way I can create the test class for this method?

You should definitely be able to use standard Http Callout Mock:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm
The only difference would be that you'd only set stats code:
// Create a fake response
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
return res;
and check for response code:
System.assertEquals(200, res.getStatusCode());

Related

Forbidden 403 response from Google Calendar API while calling from Salesforce Using Server-to-Server

I'm trying to insert an event on Google Calendar using REST API, I'm using JWT to get the access token as I don't want user to login into google account to get token. I'd performed below steps, but still getting the error:
I've created one service account
I'm getting a Token from google to send the request
I've shared the calendar with Service Account email address as well.
Please see below code:
public class GoogleCalendarSynchronization {
public static void addEvent (){
String accessToken = GenerateJWTBearerToken.generateTokenforGoogleCalendarServices();
system.debug(accessToken);
String createEventEndPoint = 'https://www.googleapis.com/calendar/v3/calendars/primary/events/';
String createEventBody = '{' +
'"attendees": ['+
'{'+
'"email": "abc#gmail.com"'+
'},'+
'{'+
'"email": "abc#gmail.com"'+
'}'+
'],'+
'"end": {'+
'"dateTime": "2019-12-27T03:30:00-07:00"'+
'},'+
'"start": {'+
'"dateTime": "2019-12-27T03:30:00-06:00"'+
'},'+
'"summary": "Appointment has been confirmed..!!",'+
'"location": "TEST",'+
'"sendUpdates": "all"'+
'}';
//system.debug(createEventBody);
Http http = new Http();
HttpRequest httpReq = new HttpRequest();
HttpResponse HttpRes = new HttpResponse();
httpReq.setEndpoint(createEventEndPoint);
httpReq.setMethod('POST');
httpReq.setBody(createEventBody);
httpReq.setHeader('Content-Type', 'application/json');
httpReq.setHeader('Authorization','Bearer ' + accessToken);
try{
HttpRes = http.send(httpReq);
if(HttpRes.getStatusCode() == 200){
String response = HttpRes.getBody();
system.debug(response);
Map<String, Object> responseMap = (Map<String, Object>)JSON.deserializeUntyped(response);
system.debug(responseMap.get('id'));
system.debug('calendar is saved successfully..!!');
}else{
String errorMessage = 'Unexpected Error while communicating with Google Calendar API. '
+'Status '+HttpRes.getStatus()+' and Status Code '+HttpRes.getStatuscode();
system.debug(errorMessage);
}
} catch(system.Exception e){
System.debug('#### Exception Executed : '+e.getMessage() + ' ' + e.getStackTraceString() + ' ' +e.getLineNumber());
}
}
}

Unable to Upload the File into DropBox From Salesforce Using /Files_put API?

I tried to upload the file into Drop Box account From Salesforce Using /files_put Dropbox Api. But am always getting following Error :
[Status=Bad Request, StatusCode=400]{"error": "Body may not be empty"}.
Hereby My Code as follows,
public class DropboxController
{
public Blob FileBody{get;set;}
public DropboxController()
{
}
public PageReference DropAuth()
{
HttpRequest request = new HttpRequest();
request.setMethod('POST');
request.setTimeout(60000); request.setEndpoint('https://apicontent.dropbox.com/1/files_put/auto/Test.txt');
Blob val = csvFileBody;
Blob accesstoken = Blob.valueOf('<redacted>');
String AccToken = 'Bearer ' + EncodingUtil.base64Encode(accesstoken);
request.setHeader('Authorization', AccToken);
request.setBodyAsBlob(val);
System.debug(val);
Http hp = new Http();
HttpResponse response = hp.send(request);
System.debug(' RESP ::: ' +response +''+ response.getBody());
return null;
}
}
Please advise .
Thanks,
Vivek.K

System.CalloutException: For input string: "password#app.fluidsurveys.com"

I am trying to access the fluid survey API in Sales force. I use the following code but it responds with an error.
The code for controller class is:
public class fluidSurvey{
public String tst{set;get;}
public String result{get;set;}
public PageReference chk() {
//if (!ApexPages.hasMessages())
result=getData();
return null;
}
public String getData()
{
HttpRequest req= new HttpRequest();
Http http = new Http();
req.setMethod('GET');
String url = 'https://username:password#app.fluidsurveys.com/api/v2/surveys/';
req.setEndpoint(url);
HttpResponse res = http.send(req);
String json = res.getBody().replace('\n','');
tst = json;
try {
JSONObject j = new JSONObject( json );
return parseJson(j);
} catch (JSONObject.JSONException e) {
return 'Error parsing JSON response from Google: '+e;
}
}
public String parseJson(JSONObject resp){
String detail =resp.getString('total');
return detail;
}
}
and the code for apex page is:
<apex:page controller="fluidSurvey">
<!-- Begin Default Content REMOVE THIS -->
<h1>Fluid Survey</h1>
<apex:form >
<apex:outputText value="{!tst}"></apex:outputText>
<apex:commandButton value="Submit" action="{!chk}"/>
</apex:form>
</apex:page>
but when I click the submit button it create the following error:
System.CalloutException: For input string: "password#app.fluidsurveys.com"
Error is in expression '{!chk}' in component <apex:page> in page fluid-page
You need to explicitly set the Authorization header.
Try the following code:
public String getData()
{
HttpRequest req= new HttpRequest();
Http http = new Http();
req.setMethod('GET');
String authString = 'username:password';
String url = 'https://app.fluidsurveys.com/api/v2/surveys/';
req.setEndpoint(url);
req.setHeader('Authorization', 'BASIC ' + EncodingUtil.base64Encode(Blob.valueOf(authString)));
HttpResponse res = http.send(req);
String json = res.getBody().replace('\n','');
try {
JSONObject j = new JSONObject( json );
return parseJson(j);
} catch (JSONObject.JSONException e) {
return 'Error parsing JSON response from Google: '+e;
}
}
I don't believe you can use the username:password#host format to pass authenticate info in the URL for Callouts, you have to explicitly set an Authentication HTTP header in your request to pass the credentials instead. (exactly how you do this will depend on what authentication types the server supports)

using HTTPRequest setPayload in google app engine

I am trying to do HTTPRequest Post via Google App Engine.
This is what I have so far
URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(########);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
Here I need to put some paired values (ie. "email","hi#example.com" etc)
Since setPayload accept byte[] I have no idea how to convert my paired values
into byte.
I have searched other posts but I am very stuck.
EDIT:
I have changed to this but it is still not working
byte[] data = ("EMAIL=bo0#gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000;").getBytes();
try {
URL url = new URL("http://www.bo.x10.mx/nPost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
This is what I have on php website.
<?php
include "path/conf.php"; //logging into database works
$tb_name = 'Post';
$EMAIL=$_POST['EMAIL'];
$TITLE =$_POST['TITLE'];
$COMMENT =$_POST['COMMENT'];
$PRICE =$_POST['PRICE'];
if(!isset($EMAIL) || !isset($TITLE ) || !isset($PRICE )|| !isset($COMMENT)){
header('HTTP/1.0 412 Precondition Failed', true, 412);
die('Bad data');
}
$sql="INSERT INTO $tb_name(EMAIL, TITLE, COMMENT, PRICE) VALUES ('$EMAIL', '$TITLE ', '$COMMENT ', '$PRICE ')";
$result=mysql_query($sql);
if($result==TRUE){
echo "successfully inserted into table!";}
else{
echo "error in inserting into table!";
header('HTTP/1.0 500 Internal Server Error', true, 500);}
ob_end_flush();
exit();
?>
EDIT2: This is a working code
try{
byte[] data = ("EMAIL=bo0#gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000").getBytes("UTF-8");
URL url = new URL("http://www.box.com/nost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
}
My database string field is of type UTF-8
You create a String with the request body, and then you get the byte array. For example we have:
URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
String body = "email=" + email + "&mpla=" + mpla;
request.setPayload(body.getBytes("UTF-8"));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
Hope this helps!

Silverlight HTTP POST

I am just trying to perform an http post on http://www.test.com/test.asp?test1=3. Here is the code I have been trying to use:
private void pif_test_conn()
{
Uri url = new Uri("http://www.test.com/test.asp?test1=3", UriKind.Absolute);
if (httpResult == true)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
}
return ;
}
private void ReadCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream()))
{
string resultString = streamReader1.ReadToEnd();
MessageBox.Show("Using HttpWebRequest: " + resultString, "Found", MessageBoxButton.OK);
}
}
When I execute this code my program triggers the Application_UnhandledException event. Not sure what I am doing wrong.
Are you trying to post to another host? That behavior could lead to XSS security problems, so that isnt available.
string responseValue = "";
AutoResetEvent syncRequest = new AutoResetEvent(false);
Uri address = new Uri(HtmlPage.Document.DocumentUri, "/sample.aspx");
WebRequest request = WebRequest.Create(address);
request.Method = "POST";
request.BeginGetRequestStream(getRequestResult =>
{
// Send packet data
using (Stream post = request.EndGetRequestStream(getRequestResult))
{
post.Write(buffer, 0, buffer.Length);
post.Close();
}
// wait for server response
request.BeginGetResponse(getResponseResult =>
{
WebResponse response = request.EndGetResponse(getResponseResult);
responseValue=new StreamReader(response.GetResponseStream()).ReadToEnd();
syncRequest.Set();
}, null);
}, null);
syncRequest.WaitOne();
MessageBox.Show(
"Using WebRequest: " + responseValue,
"Found", MessageBoxButton.OK);
HTH
You can only send HTTP requests to the domain that your app comes from.
This restriction prevents XSS attacks.
With regard to Rubens' answer,
If you leave in the SyncRequest.WaitOne() call, the call deadlocks, at least in Silverlight 4.0.
In order to send an HTTP POST, you need to write the POST data to the request by calling the BeginGetRequestStream method.
This is probably why you're getting an exception; please tell us what exception you're geting for a more specific answer.

Resources