I am new in xamarin and visual studio,I have followed this tuto from microsoft:
enter link description here
to create a cross platform application,but I get this error:
'HttpWebRequest' does not contain a definition for 'GetResponseAsync' and no extension method 'GetResponseAsync' accepting a first argument of type 'HttpWebRequest' was found (a using directive or an assembly reference is it missing * ?)
and this is my code in which I get this error:DataService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace shared
{
//This code shows one way to process JSON data from a service
public class DataService
{
public static async Task<dynamic> getDataFromService(string queryString)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(queryString);
var response = await request.GetResponseAsync().ConfigureAwait(false);
var stream = response.GetResponseStream();
var streamReader = new StreamReader(stream);
string responseText = streamReader.ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(responseText);
return data;
}
}
}
Please how can I solve it, I checked the HttpWebRequest documentation but I didn't get well the problem
thanks for help
Not sure about HttpWebRequest - but a newer and now recommended way to get data is the following:
public static async Task<dynamic> getDataFromService(string queryString)
{
using (var client = new HttpClient())
{
var responseText = await client.GetStringAsync(queryString);
dynamic data = JsonConvert.DeserializeObject(responseText);
return data;
}
}
Try that and let me know if it works.
Related
I am using this code to get form's sumbitted data from formstack
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net; //webClient
using System.IO; // use for StreamReader
namespace Test_to_integrate_FormStack
{
class Program
{
static void Main(string[] args)
{
var uri = string.Format("https://www.formstack.com/api/v2/submission/:313004779.json");
try
{
using (var webClient = new WebClient())
{
webClient.Headers.Add("Accept", "application/json");
webClient.Headers.Add("Authorization", "apikey" + "4D6A94162B2");
string Response = string.Empty;
Response = webClient.DownloadString(uri);
}
}
catch (WebException we)
{
using (var sr = new StreamReader(we.Response.GetResponseStream()))
{
}
}
}
}
}
It is giving me error:The remote server returned an error: (400) Bad Request.
Where should I wrong? Please do let me know.
Thank You
I know its late in the game, but the authentication looks incorrect to me.
It should be "Bearer [API KEY]"
Your URL is incorrect.
You used: https://www.formstack.com/api/v2/submission/:313004779.json
but it should be: https://www.formstack.com/api/v2/submission/313004779.json
https://developers.formstack.com/reference#submission-id-get
The documentation shows /:id and that means it expects a variable.
https://www.formstack.com/api/v2/submission/id.json
I'm pretty new to C# and this is my first time getting data from an api. I was wondering how do I get or call the data collected in this api request (MakeRequest). Preferably assign the data to a public string. The data from the api request is in json format.
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;
namespace CSHttpClientSample
{
public partial class Form1 : Form
{
public async void MakeRequest()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");
// Request parameters
queryString["seasonId"] = "{string}";
var uri = "https://www.haloapi.com/stats/{title}/servicerecords/arena?players={players}&" + queryString;
var response = await client.GetAsync(uri);
}
}
}
So if the call succeeded, you should have your JSON string returned in the response variable you assign in the last line.
Use your debugger and inspect that variable. If you look at the MSDN doc for your GetAsync() method (Link), you can easily find out that the variable is of the type HttpResponseMessage. This class has an own page here telling you that there's a property Content.
This is your JSON string, now might come the part where you have to do some deserializing. Have fun.
I've tried implementing the simplest case of this with a call to Mandrill's API using the method "ping." The response should be pong. Using a valid key, the response seems to work. However, I am having trouble accessing the content of the response.
The code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
namespace MandrillAPI
{
class Program
{
static void Main(string[] args)
{
string ping = "https://mandrillapp.com/api/1.0/users/ping.json";
string key = "?key=123";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ping);
HttpResponseMessage response = client.GetAsync(key).Result;
Console.WriteLine(response.ToString());
Console.Read();
}
}
}
How do I unpack the response from the call? Ultimately, I need to harvest emails from the server using the API, so I'll need to somehow preserve the structure of the json objects so I can access the details of the email.
If you just want to read the response as a string:
string content = response.Content.ReadAsStringAsync().Result
If you want to deserialize to some class (in this case the type MyClass):
MyClass myClass = JsonConvert.DeserializeObject<MyClass>(response.Content.ReadAsStringAsync().Result)
I would use something like JSON.Net to serialize it to a C# object that you can then use.
I'm building a Windows Store app, but I'm stuck at getting a UTF-8 response from an API.
This is the code:
using (HttpClient client = new HttpClient())
{
Uri url = new Uri(BaseUrl + "/me/lists");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Accept", "application/json");
HttpResponseMessage response = await client.SendRequestAsync(request);
response.EnsureSuccessStatusCode();
string responseString = await response.Content.ReadAsStringAsync();
response.Dispose();
}
The reponseString always contains strange characters which should be accents like é, and I tried using a stream, but the API I found in some examples don't exist in Windows RT.
Edit: improved code, still same problem.
Instead of using response.Content.ReadAsStringAsync() directly you could use response.Content.ReadAsBufferAsync() pointed by #Kiewic as follows:
var buffer = await response.Content.ReadAsBufferAsync();
var byteArray = buffer.ToArray();
var responseString = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
This is working in my case and I guess that using UTF8 should solve most of the issues. Now go figure why there is no way to do this using ReadAsStringAsync :)
Solved it like this:
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))
{
var byteArray = await response.Content.ReadAsByteArrayAsync();
var result = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
return result;
}
}
I like El Marchewko's approach of using an extension, but the code did not work for me. This did:
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace WannaSport.Data.Integration
{
public static class HttpContentExtension
{
public static async Task<string> ReadAsStringUTF8Async(this HttpContent content)
{
return await content.ReadAsStringAsync(Encoding.UTF8);
}
public static async Task<string> ReadAsStringAsync(this HttpContent content, Encoding encoding)
{
using (var reader = new StreamReader((await content.ReadAsStreamAsync()), encoding))
{
return reader.ReadToEnd();
}
}
}
}
Perhaps the problem is that the response is zipped. If the content type is gzip, you will need decompress the response in to a string. Some servers do this to save bandwidth which is normally fine. In .NET Core and probably .NET Framework, this will automatically unzip the response. But this does not work in UWP. This seems like a glaring bug in UWP to me.
string responseString = await response.Content.ReadAsStringAsync();
This thread gives a clear example of how to decompress the response:
Compression/Decompression string with C#
The HttpClient doesn't give you a lot of flexibility.
You can use a HttpWebRequest instead and get the raw bytes from the response using HttpWebResponse.GetResponseStream().
Can't comment yet, so I'll have to add my thoughts here.
You could try to use _client.GetStringAsync(url) as #cremor suggested, and set your authentication headers using the _client.DefaultRequestHeaders property.
Alternatively, you could also try to use the ReadAsByteArrayAsync method on the response.Content object and use System.Text.Encoding to decode that byte array to a UTF-8 string.
My approach using an Extension:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Web.Http;
namespace yourfancyNamespace
{
public static class IHttpContentExtension
{
public static async Task<string> ReadAsStringUTF8Async(this IHttpContent content)
{
return await content.ReadAsStringAsync(Encoding.UTF8);
}
public static async Task<string> ReadAsStringAsync(this IHttpContent content, Encoding encoding)
{
using (TextReader reader = new StreamReader((await content.ReadAsInputStreamAsync()).AsStreamForRead(), encoding))
{
return reader.ReadToEnd();
}
}
}
}
okay so I have a c# console source code I have created but it does not work how I want it to.
I need to post data to a URL the same as if I was going to input it an a browser.
url with data = localhost/test.php?DGURL=DGURL&DGUSER=DGUSER&DGPASS=DGPASS
Here is my c# script that does not do it the way I want to I want it to post the data as if I had typed it like above.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string URL = "http://localhost/test.php";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["DGURL"] = "DGURL";
formData["DGUSER"] = "DGUSER";
formData["DGPASS"] = "DGPASS";
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responsefromserver);
webClient.Dispose();
}
}
}
I have also triead another method in c# this does now work either
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string URI = "http://localhost/test.php";
string myParameters = "DGURL=value1&DGUSER=value2&DGPASS=value3";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "text/html";
string HtmlResult = wc.UploadString(URI, myParameters);
System.Threading.Thread.Sleep(500000000);
}
}
}
}
I have been trying to figure a way to do this in my c# console for days now
Since what you seem to want is a GET-request with querystrings and not a POST you should do it like this instead.
static void Main(string[] args)
{
var dgurl = "DGURL", user="DGUSER", pass="DGPASS";
var url = string.Format("http://localhost/test.php?DGURL={0}&DGUSER={1}&DGPASS=DGPASS", dgurl, user, pass);
using(var webClient = new WebClient())
{
var response = webClient.DownloadString(url);
Console.WriteLine(response);
}
}
I also wrapped your WebClient in a using-statement so you don't have to worry about disposing it yourself even if it would throw an exception when downloading the string.
Another thing to think about is that you might want to url-encode the parameters in the querystring using WebUtility.UrlEncode to be sure that it doesn't contain invalid chars.
How to post data to a URL using WebClient in C#: https://stackoverflow.com/a/5401597/2832321
Also note that your parameters will not appear in the URL if you post them. See: https://stackoverflow.com/a/3477374/2832321