Json Webservice Call in Apex Salesforce - json

Can anyone share an end to end example for making a JSON webservice Call Through Apex ( Visual Force Pages and Controllers ) in Salesforce .
Pretty Much like we do in HTML5 ,Jquery by Ajax !

There are examples right in the documentation of calling REST web services.
From HTTP Classes:
public class HttpCalloutSample {
// Pass in the endpoint to be used using the string url
public String getContent(String url) {
// Instantiate a new http object
Http h = new Http();
// Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');
// Send the request, and return a response
HttpResponse res = h.send(req);
return res.getBody();
}
}
You can change the method to one of:
GET, POST, PUT, DELETE, TRACE, CONNECT, HEAD, and OPTIONS
A more complete example is available at HTTP (RESTful) Services
There is also support for JSON deserialization.
Don't forget to use the Remote Site Settings to open up access to the target domain.
For a SOAP web service you can define Apex classes from a WSDL.

Related

How to authenticate HTML-5 Audio download request against Web API / Asp.Net Identity?

I need to stream audio from my Web API. In standard HTML-5 audio src attribute is set to URI of the audio from WebAPI.
Problem is: Web API secured with Asp.Net Identity requires bearer token to be passed in the headers, however HTML AUDIO TAG doesn't allow us to do. I am finally left out with two alternatives:
Approach 1. Download the HTML using XHR request & play locally.
Approach 2. Pass headers via query string. So that we could inject the
token into OWIN pipeline at point of time during request processing.
First approach mentioned above is not viable, because if we download the audio locally we would miss out streaming features provided by Web API.
Could you please assist with approach-2 i.e. so that on Web API side we could read bearer token from URL & then initiate Asp.Net Identity Authentication?
Create this provider class
public class QueryStringOAuthBearerProvider : OAuthBearerAuthenticationProvider
{
public override Task RequestToken(OAuthRequestTokenContext context)
{
var value = context.Request.Query.Get("access_token");
if (!string.IsNullOrEmpty(value))
{
context.Token = value;
}
return Task.FromResult<object>(null);
}
}
Use it in Startup.cs
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
//app.UseOAuthBearerTokens(OAuthOptions); // old line
app.UseOAuthAuthorizationServer(OAuthOptions); // new line
// Enable the application to retrieve tokens from query string to authenticate users
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
Provider = new QueryStringOAuthBearerProvider()
});
Now it will get token from url "..../?access_token=xxxxxxx" like that and try it to validate.

WinRT use HttpClient to call Web API based URL with token

We are building a WinRT app which gets data from server which is Web API based & so it gives data in json and/or XML format.
When app user logs in for the first time using his credentials(username,password), the response that comes from server is a success bit & a TOKEN, which should be used in successive URL requests.
I am using httpclient for sending requests
using (HttpClient httpClient1 = new HttpClient())
{
string url = "http://example.com/abc/api/process1/GetLatestdata/10962f61-4865-4e7a-a121-3fdd968824b5?employeeid=6";
//The string 10962f61-4865-4e7a-a121-3fdd968824b5 is the token sent by the server
var response = await httpClient1.GetAsync(new Uri(url));
string content = await response.Content.ReadAsStringAsync();
}
Now the response that i get is with status code 401 "unauthorised".
And the xml i get in response is "Unauthorised User".
Is there anything i need to change in appManifest??
I've checked this, but cant we use httpclient without credentials??
Your Capabilities are enough. You don't even need Internet (Client) because it's included in Internet (Client & Server).
You do not have credentials for WinRT HttpClient, in your linked post they referr to System.Net.Http.HttpClientHandler.
Maybe you can use the HttpBaseProtocolFilter to add the credentials?
using (var httpFilter = new HttpBaseProtocolFilter())
{
using (var httpClient = new HttpClient(httpFilter))
{
httpFilter.ServerCredential...
}
}
I don't know your security mechanism, I'm using a HttpClient and my session-key is in a cookie. But I think your client code looks fine.

ASP.NET Web API: How to do a Post back results with redirection

I got a Web API that performs a function and posts a JSON response back to a calling page.
This is standard Web API behaviour and works beautifully.
Now I want to modify the controller so that in addition to the post back the user is redirected back to the page on the calling web site where the result of the Web API call can be displayed (in JSON).
So basically I want to:
(1) Server side post back the results in JSON to a page and redirect to the same page from the Web API
(2) On the caller's site, I want to display the JSON that was posted back.
How do I do this?
I already tried for many hours ...
e.g.:
using (WebClient client = new WebClient())
{
client.Headers.Add("Content-Type", "text/json");
client.Headers.Add("Accept", "text/json");
try
{
ErrorText = client.UploadString(redirectURL, "POST", JsonConvert.SerializeObject(orderresponse));
Response.Redirect(redirectURL);
}
catch (WebException err)
{
ErrorText = err.Message; //Todo - write to logfile
}
}
Instead of doing the redirect on the server, instruct the client to do it by using the appropriate HTTP status code. For example:
public HttpResponseMessage Post(MyModel model)
{
// handle the post
MyResult result = ...;
// redirect
var response = Request.CreateResponse<MyResult>(HttpStatusCode.Moved, result);
response.Headers.Location = new Uri("http://www.yourdomain.com/redirectURI");
return response;
}

Yahoo Mail JSON API Invalid JSON

I am trying to use Java Scribe Library to integrate with Yahoo Web Service. I was able to get the OAuth Integration done.
Now I am trying to call the ListMessages JSON API using sample request in here http://developer.yahoo.com/mail/docs/user_guide/JSON-RPCEndpoint.html#
My code looks like this:
Token requestToken = buildTokenFromDB();
OAuthService service = new ServiceBuilder().provider(YahooApi.class).apiKey(API_KEY).apiSecret(API_SECRET).build();
OAuthRequest request = new OAuthRequest(Verb.GET,
"http://mail.yahooapis.com/ws/mail/v1.1/jsonrpc");
String str = getFilesAsString("msg.json");
request.addPayload(str);
request.addHeader("Content-Type", "application/json");
request.addHeader("Accept", "application/json");
service.signRequest(accessToken, request);
Response response = request.send();
I am getting the following error:
{"result":null,"error":{"code":"Client.InvalidRequest","message":"Invalid Json.","detail":null}}
Looks like I can only use GET, but I am not sure if I need to use some param for payload or scribe does it automatically.
Thanks.
Geeth

How to get JSON from a WCF Data Services, DataServiceQuery call in Silverlight?

Background: I have a WCF Data Service with a Silverlight application that is currently using atom pub xml. I want to use JSON to lessen the size of the payload.
I read that you can JSON from the service webget using the following code:
WebClient wc = new WebClient();
wc.Headers["Accept"] = "application/json";
Can I modify the header for a DataServiceQuery call or a localContext.BeginExecute (for WebGets)?
// WCF Data Services Query Proxy
DataServiceQuery<T> query = filterExpression as DataServiceQuery<T>;
// Execute the ASYNC query against the model
query.BeginExecute(new AsyncCallback((iar) =>
{ ...});
or
// Create new context with the WCF service to force only save this entity
VisiconnEDM localContext = new VisiconnEDM(new Uri(entityServiceURL, UriKind.Absolute));
// execute the query asynchronously
localContext.BeginExecute<T>(urlQuery,(IAsyncResult iar) =>{ ...},null);
Even if you would modify the header for DataServiceRequest the client library of WCF DS doesn't have support for reading JSON responses, so it would not be able to read the response. The currently suggested approach to decrease the payload size is to use GZip.