Xamarin native shared project HttpClient does not work - xamarin.ios

I have created Xamrin native shared project supporting Android and iOS mobile platforms. I want to consume REST services in both mobile apps. If I make request to REST API using HttpClient then it does not works. Gives me response as:
{StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content:
System.Net.Http.StreamContent, Headers: { Vary: Accept-Encoding
Server: DPS/1.0.3 X-SiteId: 1000 Set-Cookie: dps_site_id=1000; path=/
Date: Wed, 27 Jul 2016 12:09:00 GMT Connection: keep-alive
Content-Type: text/html; charset=utf-8 Content-Length: 964 }}
Content: {System.Net.Http.StreamContent} Headers: {Vary:
Accept-Encoding Server: DPS/1.0.3 X-SiteId: 1000 Set-Cookie:
dps_site_id=1000; path=/ Date: Wed, 27 Jul 2016 12:09:00 GMT
Connection: keep-alive } IsSuccessStatusCode: false ReasonPhrase:
"Not Found" StatusCode: System.Net.HttpStatusCode.NotFound Version:
{1.1} Non-public members:
If I uses HttpWebResponse to make request it successfully gets data.
Can you please tell why HttpClient is not working ?
// Using HttpClient
public async Task<string> GetCategories11(string token)
{
using (HttpClient client = new HttpClient())
{
var url = string.Format("{0}{1}", BaseUrl, CategoriesEndPoint);
var uri = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
try
{
using (var response = await client.GetAsync(uri))
{
if (response.IsSuccessStatusCode)
{
var contentStr = await response.Content.ReadAsStringAsync();
return contentStr;
}
else
return null;
}
}
catch
{
return null;
}
}
}
// Using HttpWebRequest
public async Task<ResponseModel> GetCategories(string token)
{
// Create an HTTP web request using the URL:
var url = string.Format("{0}{1}", RequestClient.BaseUrl, CategoriesEndPoint);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + token);
request.Accept = "application/json";
request.Method = "GET";
try
{
// Send the request to the server and wait for the response:
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response.
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON object.
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
return new ResponseModel() { Success = true, ResponseValue = jsonDoc.ToString(), StatusCode = response.StatusCode };
}
}
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
return new ResponseModel() { ResponseValue = reader.ReadToEnd(), StatusCode = ((HttpWebResponse)ex.Response).StatusCode };
}
}
catch (Exception ex)
{
return new ResponseModel() { ResponseValue = ex.Message };
}
}

Debug through and pause on line using (var response = await client.GetAsync(uri)) what is uri? and it is the same as in GetCategories()?
If you prefer, this is the method I use from Xamarin.Android and it works with a bearer token. Change to suit your needs, you may not need to do the JsonConvert.DeserializeObject() part.
protected async Task<T> GetData<T>(string dataUri, string accessToken = null, string queryString = null)
{
var url = baseUri + "/" + dataUri + (!string.IsNullOrEmpty(queryString) ? ("?" + queryString) : null);
try
{
using (var httpClient = new HttpClient() { Timeout = new TimeSpan(0, 0, 0, 0, SharedMobileHelper.API_WEB_REQUEST_TIMEOUT) })
{
// Set OAuth authentication header
if (!string.IsNullOrEmpty(accessToken))
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (HttpResponseMessage response = await httpClient.GetAsync(url))
{
string content = null;
if (response != null && response.Content != null)
content = await response.Content.ReadAsStringAsync();
if (response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Created)
{
if (content.Length > 0)
return JsonConvert.DeserializeObject<T>(content);
}
else if (response.StatusCode == HttpStatusCode.InternalServerError)
{
throw new Exception("Internal server error received (" + url + "). " + content);
}
else
{
throw new Exception("Bad or invalid request received (" + url + "). " + content);
}
}
}
}
catch (Exception ex)
{
Log.Error("Could not fetch data via GetData (" + url + ").", ex.ToString());
throw ex;
}
return default(T);
}

Related

How to add headers in node.js

I have the following headers:
X-NewRelic-ID: VQACUF9bCBABU1JQAAQPU1I=
X-Device-Descriptor-Id: YWY1Zjk5OGI5N2U1ODg0Zg
User-Agent: Sahibinden-Android/4.5.2 (671; Android 5.1.1; Android Android SDK built for x86)
x-api-key: e91092ad5ea2e030c201ce9ac4373f6b565a7842
x-client-profile: Generic_v2.1
x-device-id: d4dc022224a74bc7964cb4d449cd32c2
x-timestamp: 1591117620862
x-api-hash: DF7AB8944EDB3140BCB2A3EA9BC95F70C3200DB7
adid: b165e39f-b0ee-4b22-aee5-df3675136c2c
Content-Type: application/json; charset=utf-8
X-J3PopQvX-e: a;grA22x5m7f3tr-0iQLVuq4BLsOW3uMVgYrreUpRM5M9sSufn0I0K5QO-LrGIm1gY8IHM_GtH_7uQ-cRTU-eV9762ivhZAOpU0I2ZC_dii-H-LDjjBUj8dI1uMmlx8sJjURVN1NWhJuf7iYYkopysE4rI5Ku0OAq-vv8po6yl7vF6KA4c1JEoyeJHX0WImy3c4SV30gzj4fLe1HfYlsA1Qa3ea7pl6kE4fXnYZ0q9DbWcxT_xUBj2Hx7GPYqqdOy8LK2eVQtj_qIyBqlUMu_B1WBteBo8JpEDsCN6hVZVVOmCvzBFVrJgh3rXd-bz3J6-TAgFOgIlbKEob6SrxPFvmrjrjFz2CESgBYUe2YBkwzOMYiNfRLfYKRF9bifV53JcX25D6ycfE5wp72kRvUDsF049QUgUyEvAOIdZcOTbETQtoAOIYtvClrsZQ8lI8VuKpHaqm3z0Cz59jNvXDYSIyVGQ43BbFHYJmvuVDK5hms8YQe1AU4z-kWFEZbR1GI2SD3e1ivl5a8YQNj3YLId6HeHy1BZZ4vrMfKhRmW6RFz3E8--TDu3r9J_RyYOh7_UhJ6-KW1FQ4mnoAD-1ObhBgw7VvefrijzY6iQKbnVhR2GVs0eAMv8RvON81vgIE7eZvqv4TFbNfpFzbNDYE4JboRsrroyElH9kbRkh6xc8Y_dlXZnZqHZH8Z55f1rBAQjeci9YzxGUJ4ssJE2vlniRkU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VNRCukPDJeRSSYr4iCM5=-3UzYPSDwkb=_7Ea=WvgXvKtIeKbYcF5ZPk8OU-rq_ysU2Slfaf7fgHHR4Aif2cx_ZTekL=0W5LQL3AZv2QBh-VjjNri
X-J3PopQvX-b: -1o1lvb
X-J3PopQvX-c: AEC_kwhyAQAA125LdUCpBmDn_gaT36bu5R1v7tLmaWD2Y_AhYfLAeVsrDVYa
X-J3PopQvX-d: o_2
X-J3PopQvX-f: AyT1lAhyAQAA645HTYkhB4gLDM5zokBx1RSq1NMZ34yfPEFY650x2JWUiytPAWf_BDWcuH01wH8AAEB3AAAAAA==
X-J3PopQvX-z: p
Host: api.sahibinden.com
Connection: Keep-Alive
Accept-Encoding: gzip
With each request I want to be able to regenerate following headers:
X-J3PopQvX-a
X-J3PopQvX-b
X-J3PopQvX-c
X-J3PopQvX-d
X-J3PopQvX-f
X-J3PopQvX-z
I know of XMLHttpRequest but Im not sure how to use it in this case. I am new to node.js so a bit clueless
Edit:
I am able to send my headers using this : try {
let res = await httpClient.get(url, {
headers: headers,
params: query,
});
But I want to change j3pop headers everytime I send them. Need to change them manually. Is there any way for that?
Edit1:
This code here generates new headers:
function() {
'use strict';
console.log("inside");
var afterReadyCbCalled = false;
var originalHeaders = ["X-Origin-DC", "gytp","Cache-Control", "max-age=0","X-Forwarded-For", "103.255.4.53","X-Client-SrcPort", "45244","Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","Accept-Language", "en-US,en;q=0.5","X-Forwarded-Proto", "https","X-TLS-Version", "771","Upgrade-Insecure-Requests", "1","ISTL-REFERER", "https://www.sahibinden.com/",];
var originalBody = "";
function afterReadyCb() {
if (afterReadyCbCalled) return;
afterReadyCbCalled = true;
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var isValid = xhr.getResponseHeader("ISTL-INFINITE-LOOP");
if (isValid != null && isValid != '') return;
var a = xhr.getResponseHeader("ISTL-REDIRECT-TO");
if (a != null && a != '') {
location.replace(a);
} else {
if (window.history != null && typeof history.replaceState === 'function') {
var responseURL = xhr.responseURL != null ? xhr.responseURL : xhr.getResponseHeader("ISTL-RESPONSE-URL");
if (responseURL != null && responseURL != '') {
history.replaceState(null, '', responseURL);
}
}
document.open();
document.write(xhr.responseText);
document.close();
}
};
xhr.open("get", location.href, true);
for (var i = 0; i < originalHeaders.length; i += 2) {
var headerName = originalHeaders[i];
try {
xhr.setRequestHeader(headerName, originalHeaders[i + 1]);
} catch (e) {}
}
xhr.setRequestHeader("ISTL-INFINITE-LOOP", '1');
xhr.send(originalBody);
var evt = document.createEvent('Event');
evt.initEvent('QLpZFJdHv', true, true);
dispatchEvent(evt);
}
addEventListener('afterReady', afterReadyCb, false);
setTimeout(afterReadyCb, 400);
}());
Code is extracted from website by simply saving the html. Here is the link to website : https://www.sahibinden.com/
Here a sample code:
function doScrapRequest (postData, onSuccessCallback, onErrorCallback) {
var options = {
hostname: "your-host-name",
port: 443,
path: "/path-you-want-to-post-to",
method: 'POST',
headers: {
'X-J3PopQvX-a': '0JMyqk3j...',
'X-J3PopQvX-b': '-1o1lvb'
'X-J3PopQvX-c': 'AEC_kwhy...'
'X-J3PopQvX-d': 'o_2'
'X-J3PopQvX-f': 'AyT1lA...'
'X-J3PopQvX-z': 'p'
}
};
var req = https.request(options, function (res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function (chunk) {
body = body + chunk;
});
res.on('end',function(){
console.log("Body :" + body);
if (res.statusCode != 200) {
onErrorCallback("Api call failed with response code " + res.statusCode);
} else {
// If you are expecting application/json you can do JSON.parse in the body variable.
onSuccessCallback(body);
}
});
});
req.on('error', function (e) {
console.log("Error : " + e.message);
onErrorCallback(e);
});
// write data to request body
req.write(postData);
req.end();
}

Nodejs: Why is my Promise not work in PUT request? Resloved

I using that API to create resumable Upload in Drive.
It worked but i can't receive response data from Promise
Here is my code:
var fs = require('fs');
var request = require('request');
var mime = require('mime');
var _ = require("underscore");
class resumableUpload {
constructor(credentials,token,options={}){
this.credentials = credentials; // object from json credentials
this.token = token; // object from token credentials
this.new_token = {};
this.expiry_token_time = 0;
this.options = Object.assign({
size:256*1024,
retry:-1
},options)
}
refresh_token(){
return new Promise((ok,faild)=>{
var now = new Date().getTime();
if(now>this.expiry_token_time){
request.post("https://www.googleapis.com/oauth2/v4/token",{
form:{
refresh_token:this.token.refresh_token,
client_id:this.credentials.client_id,
client_secret:this.credentials.client_secret,
redirect_uri:this.credentials.redirect_uris[0],
grant_type:'refresh_token'
}
},(err,httpResponse,body)=>{
if(err) faild(err);
this.new_token = JSON.parse(body);
this.expiry_token_time = now + this.new_token.expires_in*1000;
ok(this.new_token.access_token);
})
}else{
ok(this.new_token.access_token);
}
})
}
/*
Upload Resumable
file:{
name:'name of file',
path:'path/to/file'
}
*/
upload(file){
return new Promise((ok,faild)=>{
this.refresh_token().then((access_token)=>{
console.log(access_token);
this.file_len = fs.statSync(file.path).size;
var form = {};
if(!_.isEmpty(file.name)) form.name = file.name;
if(!_.isEmpty(file.parents)) form.parents = [file.parents];
request.post({
uri:'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable',
headers:{
'Authorization':`Bearer ${access_token}`,
'Content-Type':'application/json; charset=UTF-8',
'X-Upload-Content-Type':mime.getType(file.path),
'X-Upload-Content-Length': this.file_len,
'Content-Length':new Buffer(JSON.stringify(form)).length
},
body:JSON.stringify(form)
},(err,res,body)=>{
if(err || _.isEmpty(res.headers.location)){
if ((this.retry > 0) || (this.retry <= -1)) {
this.retry--;
return this.upload(file); // retry
} else {
//console.log(body);
faild("Over retry");
}
}else{
var location = res.headers.location;
//console.log("URL UPLOAD: ",location);
this.sendUpload(location,file).then((data)=>{
console.log("UPLOAD DONE!!!");
ok(data);
}).catch((err)=>{
console.log("ERROR: ",err);
faild(err);
});
}
})
}).catch(faild)
})
}
sendUpload(api,file,start=0){
return new Promise((ok,faild)=>{
this.refresh_token().then((access_token)=>{
var end = parseInt(start+this.options.size-1);
if(start>=this.file_len) ok("DONE");
if(end>=this.file_len) end = this.file_len - 1;
var headers = {
'Authorization':`Bearer ${access_token}`,
'Content-Length': parseInt(end - start + 1),
'Content-Range':`bytes ${start}-${end}/${this.file_len}`
}
var uploadPipe = fs.createReadStream(file.path, {
start: start,
end: end
})
uploadPipe.pipe(request.put({uri:api,headers:headers}).on('response',(res)=>{
if(res.statusCode == 308){
//console.log(res.headers);
var new_start = parseInt(res.headers.range.split('-')[1]);
console.log("Percent: "+(new_start/this.file_len*100).toFixed(2)+" %");
return this.sendUpload(api,file,new_start+1);
}else if(res.statusCode == 200 || res.statusCode == 201){
console.log("percent: 100 %");
//ok({status:"OK"});
}
}).on('error',(err)=>{
if ((this.retry > 0) || (this.retry <= -1)) {
this.retry--;
console.log("Retry Again");
return this.sendUpload(api,file,start);
}else{
faild("Over retry");
}
}).on('data',(data)=>{
if(!_.isEmpty(data)){
console.log(data.toString());
ok(data.toString());
}
}))
}).catch(faild)
})
}
}
module.exports = resumableUpload;
In that code - sendUpload function, I split my file to many chunk and upload it in to drive.
when I upload the last chunk, server will response statusCode is 200 or 201.
It console.log "percent: 100 %" and received data from that response.
My data of response like it:
{
"kind": "drive#file",
"id": "xxxxxxxxxxxxxxxxxxxxxxxxx",
"name": "test-video",
"mimeType": "video/mp4"
}
But, the Resolve (ok function) not call, cause in upload function, i can't receive it in then function. it mean i can't see "UPLOAD DONE!!!" in screen.
Resloved: Thanks for Roamer-1888
In Pipe, return a promise not work. I change return this.sendUpload(...) to this.sendUpload(...).then(ok,faild) and it worked.

How to pass token from Nodejs to backend Java code

I am new to Nodejs .
I am trying to pass JWT token from Nodejs to java service class.
I am getting JWT token in a variable in Nodejs code that I need to pass to spring mvc application service class.
can anyone please help me on this?
And having confusion with how to integrate Nodejs with java if i pass variable from Nodejs to java?
Node code is,
module.exports = {
verifyReq: function (req, res, next) {
if (req.headers.authorization) {
res.setHeader('Content-Type', 'text/html');
res.write('<div id="_mscontent"><script src="URL"></script>');
var notAuthorized = false;
var authorization = req.headers.authorization;
console.log("authorization: " + authorization);
if (authorization) {
req.isAuthorized = true;
}
try {
var decodedJWT = JWT.decode(authorization.split(' ')[1], "", true);
} catch (e) {
notAuthorized = true;
}
else {
req.isAuthorized = false;
res.status(401);
res.end('Not Authorized!');
return;
}
return req.isAuthorized === true;
}
};
Java Code,
public class GetCarAssetValuesService {
private static String output;
private static String token;
private static Asset[] myObjects;
public void getAssets(String tokenToPass)
throws JsonParseException, JsonMappingException, IOException, JSONException {
System.out.println("In service");
HttpsURLConnection myURLConnection = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
StringBuilder strBuilder = new StringBuilder();
JSONObject jsonObj = new JSONObject(tokenToPass);
System.out.println("success_token= " + jsonObj);
token = jsonObj.getString("access_token");
System.out.println("Print token= " + token);
try {
URL url = new URL(
"Third Party URL");
myURLConnection = (HttpsURLConnection) url.openConnection();
String bearerAuth = "Bearer " + token;
myURLConnection.setRequestProperty("Authorization", bearerAuth);
myURLConnection.setRequestMethod("GET");
myURLConnection.setRequestProperty("Content-Type", "application/json");
myURLConnection.setDoOutput(true);
inputStream = myURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
if (myURLConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + myURLConnection.getResponseCode());
}
System.out.println("Here the control cars...");
System.out.println("Output from Server .... \n");
while ((output = bufferedReader.readLine()) != null) {
strBuilder.append(output);
System.out.println(output);
}
myURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String mindsphereResponse = strBuilder.toString();
System.out.println("Responsesssssss" + mindsphereResponse);
ObjectMapper mapper = new ObjectMapper();
myObjects = mapper.readValue(mindsphereResponse, Asset[].class);
}
Here instead of passing "tokenToPass" i want to get this token from node js i.e.decodeJWT. This "tokenToPass" i am getting from other java service now i want it from Nodejs.
Thanks in Advance..!!!
You can set the JWT token in the HTTP Request header ( nodejs ) and API endpoint ( java ) can be get it from there.
HelloController.java
#Controller
public class HomeController {
#Autowire
private HomeService homeService;
#GetMapping("/hello")
public String home(HttpServletRequest request, Model model) {
helloService.invoke(request.getHeader('JWT_TOKEN_KEY'));
}
}
HelloService.java
#Service
public class HelloService {
public void invoke(jwtToken) {
// Use this jwttoken
}
}
NodeJS.js
var options = {
host: 'your_java_api_endpoint',
port: 80,
path: '/hello',
headers:{
'JWT_TOKEN_KEY':'json web token here'
}
};
http.get(options, function(res) {
res.on("data", function(responseData) {
console.log("data: " + responseData);
});
}).on('error', function(e) {
console.log("http error : " + e);
});

Trying to import gmail contacts using node.js

I'm trying to import gmail contacts. I have successfully obtained the access_token but when trying to get the contacts browser keeps throwing the error. invalid_grant
my codes below.
for authentication and callback.
authorize: function(req, res){
var CLIENT_ID = '927112080821-vhsphqc79tb5ohfgpuvrp8uhh357mhad.apps.googleusercontent.com';
var CLIENT_SECRET = 'gdgofL0RfAXX0in5JEiQiPW8';
var SCOPE = 'https://www.google.com/m8/feeds';
oa = new oauth.OAuth2(CLIENT_ID,
CLIENT_SECRET,
"https://accounts.google.com/o",
"/oauth2/auth",
"/oauth2/token");
res.redirect(oa.getAuthorizeUrl({scope:SCOPE, response_type:'code', redirect_uri:'http://localhost:1234/callback'}));
},
callback: function(req, res){
console.log(req.query.code);
oa.getOAuthAccessToken(req.query.code, {grant_type:'authorization_code', redirect_uri:'http://localhost:1234/callback'}, function(err, access_token, refresh_token) {
if (err) {
res.end('error: ' + JSON.stringify(err));
} else {
getContactsFromGoogleApi(access_token);
//res.write('access token: ' + access_token + '\n');
//res.write('refresh token: ' + refresh_token);
//res.end();
}
});
},
for importing contacts
function getContactsFromGoogleApi (access_token, req, res, next) {
console.log('access_token ' + access_token);
request.get({
url: 'https://www.google.com/m8/feeds/contacts/default/full',
qs: {
alt: 'json',
'max-results': 1000,
'orderby': 'lastmodified'
},
headers: {
'Authorization': 'OAuth ' + access_token,
'GData-Version': '3.0'
}
}, function (err, res, body) {
if(res.statusCode === 401){
return res.redirect('index');
}
var feed = JSON.parse(body);
var users = feed.feed.entry.map(function (c) {
var r = {};
if(c['gd$name'] && ['gd$fullName']){
r.name = c['gd$name']['gd$fullName']['$t'];
}
if (c['gd$email'] && c['gd$email'].length > 0) {
r.email = c['gd$email'][0]['address'];
r.nickname = r.email;//c['gd$email'][0]['address'].split('#')[0];
}
if(c['link']){
var photoLink = c['link'].filter(function (link) {
return link.rel == 'http://schemas.google.com/contacts/2008/rel#photo' &&
'gd$etag' in link;
})[0];
if(photoLink) {
r.picture = '/users/photo?l=' + encodeURIComponent(photoLink.href);
} else if (r.email) {
r.picture = gravatar.url(r.email, {
s: 40,
d: "https://ssl.gstatic.com/s2/profiles/images/silhouette80.png"});
}
}
return r;
}).filter(function (u) {
return !!u.email && //we can only give access to persons with email at this point
!~u.email.indexOf('#reply.'); //adress with #reply. are usually temporary reply address for forum kind of websites.
});
res.json(users);
});
}
really appreciate help.
In your getContactsFromGoogleApi function change the Authorization header to the following;
headers: {
'Authorization': 'Bearer ' + access_token,
'GData-Version': '3.0'
The following is code in C# to do the same thing
webClient = new WebClient();
webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
webClient.Headers.Add(HttpRequestHeader.Authorization, String.Format("Bearer {0}", AccessToken));
do
{
contactStream = webClient.DownloadData(String.Format("{0}?start-index={1}", BaseApiEndpoints[Applications.Contacts], startIndex));
contactDocument = System.Text.Encoding.Default.GetString(contactStream);
contacts = new XmlDocument();
contacts.LoadXml(contactDocument);
// TODO: use xsl to convert results to ContactSearchResults
xslt = new XslCompiledTransform();
resultStream = new MemoryStream();
writer = new XmlTextWriter(resultStream, Encoding.ASCII);
translateContact = new XmlDocument();
xslStream = GetRequest("GoogleContacts.xslt");
xslStream.Seek(0, SeekOrigin.Begin);
templateReader = XmlReader.Create(xslStream);
xslt.Load(templateReader);
xslt.Transform(contacts,writer);
resultStream.Seek(0, SeekOrigin.Begin);
TranslatedContacts = ConvertByteArrayToString(ReadFully(resultStream));
csr = (ContactSearchResults)Deserialize(typeof(ContactSearchResults), TranslatedContacts);
foreach (Contact contact in csr.Contacts)
{
contact.RecordId = Guid.NewGuid();
// now we want to get the image
contact.Picture = GetImage(contact.PictureUrl, AccessToken);
if ((!String.IsNullOrEmpty(contact.Name)) || (!String.IsNullOrEmpty(contact.Email)))
results.Add(contact);
}
startIndex += csr.ItemsPerPage;
} while (startIndex < totalResults);
Url I used here is the same as your code; http://www.google.com/m8/feeds/
When I did this in C# I did not need to pass the version.

Return JSON in Xamarin.iOS

I am trying to run a sample WebRequest to return JSON data. I keep on getting XML response. any idea why?
this.btnGetCoordinates.TouchUpInside += (sender, e) => {
var rxcui = "198440";
var request = HttpWebRequest.Create(string.Format (#"http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/{0}/allinfo", rxcui));
request.Method = "GET";
request.ContentType = "application/json";
request.BeginGetResponse(new AsyncCallback(ProcessGetCoordinates), request);
};
return true;
}
void ProcessGetCoordinates(IAsyncResult iar) {
HttpWebRequest request = (HttpWebRequest)iar.AsyncState;
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse (iar)) {
if (response.StatusCode != HttpStatusCode.OK) {
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
}
using (StreamReader strm = new StreamReader (response.GetResponseStream())) {
string content = strm.ReadToEnd ();
if (string.IsNullOrWhiteSpace (content)) {
Console.Out.WriteLine("Response contained empty body...");
} else {
Console.Out.WriteLine("Response Body: \r\n {0}", content);
}
}
}
}
You need to set the Accept header on your request to "application/json".
var request = HttpWebRequest.Create(string.Format (#"http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/{0}/allinfo", rxcui));
request.Method = "GET";
request.Accept = "application/json";

Resources