WinRT use HttpClient to call Web API based URL with token - windows-runtime

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.

Related

Xamarin App Sends Json Data When Phone Virtual But Doesn't Send Physical

I don't know where to look or what to check but ask my question in title. Xamarin forms app works when sending json data over virtual phone instance but doesn't send data over physical no matter which platform i use , it is the same with iOS and Android.
static async Task phoneInfo()
{
string url = "http://blabla.com/api/blabla";
string sContentType = "application/json";
JObject jsonObject = new JObject();
jsonObject.Add("DeviceModel", DeviceInfo.Model);
jsonObject.Add("DeviceManufacturer", DeviceInfo.Manufacturer);
jsonObject.Add("DeviceName", DeviceInfo.Name);
jsonObject.Add("DeviceVersion", DeviceInfo.VersionString);
jsonObject.Add("DevicePlatform", DeviceInfo.Platform);
jsonObject.Add("DeviceIdiom", DeviceInfo.Idiom);
jsonObject.Add("DeviceType", DeviceInfo.DeviceType.ToString());
jsonObject.Add("AreaOne", DateTime.UtcNow.ToString());
jsonObject.Add("Deleted", false);
HttpClient oHttpClient = new HttpClient();
var oTaskPostAsync = await oHttpClient.PostAsync(url, new StringContent(jsonObject.ToString(), Encoding.UTF8, sContentType));
}
usage is simple like code. just put await phoneInfo(); where i want to take info.
i have accesswifistate and internet permission over Android and NSAppTransportSecurity for non https connection with iOS.
Any ideas where am i doing wrong?

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.

Extracting gzip data from Apache-httpclient without decompression

I'm using apache httpclient 4.3.5 to send a request to an upstream server which returns a gzipped response. I need to pass this response AS-IS to a downstream server without any form of decompression. However, httpclient is far too helpful and insists on decompressing the response and I can't find any way of persuading it to stop.
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse serverResponse = client.execute(serverRequest);
try {
HttpEntity entity = serverResponse.getEntity();
downstreamResponse.setStatus(serverResponse.getStatusLine().getStatusCode());
for (Header header : serverResponse.getAllHeaders()) {
downstreamResponse.setHeader(header.getName(), header.getValue());
}
entity.writeTo(downstreamResponse.getOutputStream());
downstreamResponse.flushBuffer();
} finally {
serverResponse.close();
}
I'm sure that there is some way of configuring the client using some form of the construct
return HttpClients.custom()
....
.build();
but I can't find it. Can the experts please advise?
CloseableHttpClient client = HttpClients.custom()
.disableContentCompression()
.build();

Json Webservice Call in Apex Salesforce

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.

BackgroundTransferRequest DownloadLocation to get the Response content

I am uploading a file to the server using BackgroundTransferRequest object. I need to access the response header sent from the server. Based on the research, I understand that there is no direct access to the Response of the request and one possible work around is to provide a download location to which the response content will be written.
However, when I try to do that, there is no data written to that file and its 0 bytes. My request server is actually sending a response having ONLY the headers (without any content).
So my question is, does the response have to have body in order to get the response written to the DownloadLocation?
My code sample:
var request = new BackgroundTransferRequest(targetUri)
{
DownloadLocation = new Uri(downloadTo, UriKind.Relative),
UploadLocation = new Uri(uploadFrom, UriKind.Relative),
Method = "POST"
};