Sending data to a url - c#

I want to send data to a php page, which inserts it in a database. I got the following code from Sending data to php from windows phone from but it shows some errors:
On using: System.Net.WebClient: type used in a using statement
must be implicitly convertible to System.IDisposable.
On UploadString: System.Net.WebClient does not contain a definition for UploadString and no extension method UploadString
accepting a first argument of the type System.Net.WebClient could
be found (are you missing a using directive or an assembly
reference?).
Does anyone have an idea how to fix this?
string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
}

http://www.drdobbs.com/windows/writing-your-first-windows-8-app-the-lay/240143752 says HttpClient is replacing WebClient in windows 8 app
Uploadstring uses post method to send data and PostAsync is available in HttpClient which is what you might need.
try something like this.
using System.Net.Http;
//Windows.Web.Http
string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";
sendData(URI,myParameters);
public async void sendData(string URI,string myParameters)
{
using(HttpClient hc = new HttpClient())
{
Var response = await hc.PostAsync(URI,new StringContent (myParameters));
}
}

Related

Webclient does not understand blob:http uri

I am trying to download data from a blob:http link problem is the webclient complains about the url formating. blob:http://localhost/7420f6fc-9c83-43a3-aa53-4a68ebec9518 this format is not know to webclient is there another way to download this data without using Azure calls?
using (var client = new WebClient())
{
//NotSupportedException: The URI prefix is not recognized.
var model = client.DownloadData(new Uri("blob:http://localhost/7420f6fc-9c83-43a3-aa53-4a68ebec9518"));
//Also tried
var model = client.DownloadData("blob:http://localhost/7420f6fc-9c83-43a3-aa53-4a68ebec9518");
}

.NETCore HttpWebRequest - Old Way isn't Working

Before I upgraded to the newest .NetCore I was able to run the HttpWebRequest, add the headers and content Type and pull the stream of the JSON file from Twitch. Since the upgrade this is not working. I receive a Web Exception each time I go to get the response Stream. Nothing has changed with twitch because it still works with the old Bot. The old code is below:
private const string Url = "https://api.twitch.tv/kraken/streams/channelname";
HttpWebRequest request;
try
{
request = (HttpWebRequest)WebRequest.Create(Url);
}
request.Method = "Get";
request.Timeout = 12000;
request.ContentType = "application/vnd.twitchtv.v5+json";
request.Headers.Add("Client-ID", "ID");
try
{
using (var s = request.GetResponse().GetResponseStream())
{
if (s != null)
using (var sr = new StreamReader(s))
{
}
}
}
I have done some research and found that I may need to start using either an HttpClient or HttpRequestMessage. I have tried going about this but when adding headers content type the program halts and exits. after the first line here: (when using HttpsRequestMessage)
request.Content.Headers.ContentType.MediaType = "application/vnd.twitchtv.v5+json";
request.Content.Headers.Add("Client-ID", "rbp1au0xk85ej6wac9b8s1a1amlsi5");
You are trying to add a ContentType header, but what you really want is to add an Accept header (your request is a GET and ContentType is used only on requests which contain a body, e.g. POST or PUT).
In .NET Core you need to use HttpClient, but remember that to correctly use it you need to leverage the use of async and await.
Here it is an example:
using System.Net.Http;
using System.Net.Http.Headers;
private const string Url = "https://api.twitch.tv/kraken/streams/channelname";
public static async Task<string> GetResponseFromTwitch()
{
using(var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.twitchtv.v5+json"));
client.DefaultRequestHeaders.Add("Client-ID", "MyId");
using(var response = await client.GetAsync(Url))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync(); // here we return the json response, you may parse it
}
}
}

How to send multiple parameters to a Web API call using WebClient

I want to send via POST request two parameters to a Web API service. I am currently receiving 404 not found when I try in the following way, as from msdn:
public static void PostString (string address)
{
string data = "param1 = 5 param2 = " + json;
string method = "POST";
WebClient client = new WebClient ();
string reply = client.UploadString (address, method, data);
Console.WriteLine (reply);
}
where json is a json representation of an object. This did not worked, I have tried with query parameters as in this post but the same 404 not found was returned.
Can somebody provide me an example of WebClient which sends two parameters to a POST request?
Note: I am trying to avoid wrapping both parameters in the same class only to send to the service (as I found the suggestion here)
I would suggest sending your parameters as a NameValueCollection.
Your code would look something like this when sending the parameters with a NameValueCollection:
using(WebClient client = new WebClient())
{
NameValueCollection requestParameters = new NameValueCollection();
requestParameters.Add("param1", "5");
requestParameters.Add("param2", json);
byte[] response = client.UploadValues("your url here", requestParameters);
string responseBody = Encoding.UTF8.GetString(response);
}
Using UploadValues will make it easier for you, since the framework will construct the body of the request and you won't have to worry about concatenating parameters or escaping characters.
I have managed to send both a json object and a simple value parameter by sending the simple parameter in the address link and the json as body data:
public static void PostString (string address)
{
string method = "POST";
WebClient client = new WebClient ();
string reply = client.UploadString (address + param1, method, json);
Console.WriteLine (reply);
}
Where address needs to expect the value parameter.

How do i parse json with web client and display it in the console?

WebClient client = new WebClient();
string value = client.DownloadString("http://www.onemap.sg/publictransportation/service1.svc/routesolns?token=qo/s2TnSUmfLz+32CvLC4RMVkzEFYjxqyti1KhByvEacEdMWBpCuSSQ+IFRT84QjGPBCuz/cBom8PfSm3GjEsGc8PkdEEOEr&sl=39167.4524,35518.8625&el=28987.5163,33530.5653&startstop=&endstop=&walkdist=300&mode=bus&routeopt=cheapest&retgeo=true&maxsolns=1&callback=");
// Write values.
Console.WriteLine("Results:");
Console.WriteLine(value.Length);
Console.WriteLine(value);
Error message shows:
'System.Net.WebClient' does not contain a definition for 'DownloadString' and no extension method 'DownloadString' accepting a first argument of type 'System.Net.WebClient' could be found (are you missing a using directive or an assembly reference?)
In windows phone you're forced in most cases to program in an asynchronous way.
So instead of DownloadString, you have to use DownloadStringAsync as shown here in this sample:
var client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(loadHTMLCallback);
client.DownloadStringAsync(new Uri("http://www.myurl.com/myFile.txt"));
//...
public void loadHTMLCallback(Object sender, DownloadStringCompletedEventArgs e)
{
var textData = (string)e.Result;
// Do cool stuff with result
Debug.WriteLine(textData);
}
Source:
http://developer.nokia.com/community/wiki/Asynchronous_Programming_For_Windows_Phone_8
//Initialize new Client
HttpClient client = new HttpClient();
//Response will handle the returned JSON
HttpResponseMessage response;
//URI of the service
string strURI = "http://www.onemap.sg/publictransportation/service1.svc/routesolns?token=qo/s2TnSUmfLz+32CvLC4RMVkzEFYjxqyti1KhByvEacEdMWBpCuSSQ+IFRT84QjGPBCuz/cBom8PfSm3GjEsGc8PkdEEOEr&sl=39167.4524,35518.8625&el=28987.5163,33530.5653&startstop=&endstop=&walkdist=300&mode=bus&routeopt=cheapest&retgeo=true&maxsolns=1&callback=";
//String that the response will be converted to.
string strResponseJSONContent = "";
//Lets the client know to expect JSON
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Getting the JSON and saving it to response
response = client.GetAsync(strURI).Result;
//Setting response to a string
strResponseJSONContent = response.Content.ReadAsStringAsync().Result;
You will need to add using System.Net.Http and using System.Net.Http.Headers
I haven't tested this in your specific scenario or with your service but I can't see why it wont work for you as it gets the JSON asynchronously.

C# and ASP.net saving html into a string or a file

I'm new to ASP and I was wondering if there is a way to save the source of the web-page into a string variable or a .txt file given a website address using C# or ASP.net with C#.
If its possible, example code and information on what libraries to reference would be very helpful.
You can use the WebClient class for that:
To a string variable:
string result;
using (WebClient wc = new WebClient())
result = wc.DownloadString("http://stackoverflow.com");
To a file:
using (WebClient wc = new WebClient())
wc.DownloadFile("http://stackoverflow.com", #"C:\test\test.txt");
Sure thing:
HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse;
string html = new StreamReader(response.GetResponseStream()).ReadToEnd();
At a basic high level.
You should take a look at the WebClient Class
An example can be found on the link posted above.

Categories

Resources