c# sending data to php url - c#

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

Related

How can I deserialize an influxDB JSON-query to look like a table using Newtonsoft.Json?

I receive a JSON-Object from influxDB which contains the table content from the table "cpu", but the console shows up an unformatted string
{"results":[{"statement_id":0,"series":[{"name":"cpu","columns":["time","host","region","value"],"values":[["1970-01-01T00:00:01.559815781Z","serverA","us_west",95],["2019-06-06T09:59:40.68601263Z","serverA","us_west",0.64],["2019-06-06T10:09:41.790446331Z","serverA","us_west",0.78]]}]}]}
Referencing to System.Web.Script.Serialization isn't an option because I'm using .NET Core.
I put the "pretty=true" to the EscapeUriString what helps me to get a better looking JSON result.
Result after "pretty=true"
The query i'll send can be different so creating a class isn't an option too
Thats my code for so long
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net;
namespace InfluxDBQuery
{
class Program
{
static void Main(string[] args)
{
string influxURL = "http://172.29.213.151:8086/query";
string database = "mydb";
string pretty = "pretty=true&";
var client = new WebClient();
var queryString = Uri.EscapeUriString($"?{pretty}db={database}&q=SELECT * FROM cpu");
var queryUrl = influxURL + queryString;
var response = client.DownloadString(queryUrl);
Console.WriteLine(response);
dynamic json = JsonConvert.DeserializeObject(response);
Console.WriteLine(json);
}
}
}
So how can i format the result from the InfluxDB-query to look like a table?

Get submitted data from formstack using C#?

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

C# Login to a non-interactive website and pass XML via URL

Okay, so here is what I have and I am probably doing this completely wrong, but I need some more direction than what I am finding online.
I am trying to pass a URL containing login information and then pass another url in the same connection containing my XML. That's all, and I can't seem to get this to work. Please help!!
Here's my code.
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Xml;
using System.Net;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
using System.ComponentModel;
using System.Collections.Specialized;
namespace DataIntegration.DataSender
{
class RaveDataSender
{
static void Main(string[] args)
{
System.Uri myUri = new System.Uri(#"https://api.myloginpage.com/edc_studyservices.jsp?action=importfile&filecontents=<?xml version='1.0'?><dataprocessitems><item>someitem</item></dataprocessitems>&filename=1.xml");
System.Uri loginUri = new System.Uri(#"https://api.myloginpage.com/login.jsp?studyid=something&action=login&login=myLoginName&password=myPassword");
byte[] mybytes = Encoding.ASCII.GetBytes("https://api.myloginpage.com/edc_studyservices.jsp?action=importfile&filecontents=<?xml version='1.0'?><dataprocessitems><item>someitem</item></dataprocessitems>&filename=1.xml");
byte[] loginbytes = Encoding.ASCII.GetBytes(#"https://api.myloginpage.com/login.jsp?studyid=something&action=login&login=myLoginName&password=myPassword");
CookieAwareWebClient client = new CookieAwareWebClient();
client.UploadDataAsync(loginUri, loginbytes);
client.UploadDataAsync(myUri, mybytes);
client.Dispose();
}
public class CookieAwareWebClient : WebClient
{
private CookieContainer cookie = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = cookie;
}
return request;
}
}
}
}
EDIT this is what I ended up doing.
using (var client = new CookieAwareWebClient())
{
byte[] authresp = client.UploadData(loginUri, loginbytes);
byte[] dataRespose = client.UploadData(xmlUri, reqbytes);
string authResult = System.Text.Encoding.UTF8.GetString(authresp);
string result = System.Text.Encoding.UTF8.GetString(dataRespose);
client.Dispose();
}
I think the problem might be that you dispose the object while the asynchronous methods still running.

'HttpWebRequest' does not contain a definition for 'GetResponseAsync'

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.

How do I access the content of an API response?

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.

Categories

Resources