How to query InfluxDB using WebClient in C# - c#

I'm trying to write a simple query command. Documentaion for http for influxDB is here.
This is what I have so far:
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("root", "root");
var reponse = client.UploadString("http://localhost:8080/query", "db=dbName\"q = SELECT \"something\" FROM \"tableName\" WHERE \"tag\"='valueTag'");
I'm getting "The remote server returned an error: (400) Bad Request.". Is it because the urlencode is not the same as putting as the string for the data part of client.UploadString?

WebClient.UploadString sends data as part of a POST request, which isn't what you want for this operation. Instead, your query should be URL-encoded and sent as HTTP GET parameters in the request URL. This can be achieved using Uri.EscapeUriString and WebClient.DownloadString:
var client = new WebClient();
var queryString = Uri.EscapeUriString("db=dbName&q=SELECT \"something\" FROM \"tableName\" WHERE \"tag\"='valueTag'");
var queryUrl = "http://localhost:8086/query?" + queryString;
var response = client.DownloadString(queryUrl);
Also note that HTTP GET parameters are separated by an ampersand and there must not be whitespace between the key/value names and the = or &. For example ?k1=v1&k2=v2 is well-formed whereas ?k1=v1&k1 = v1 is not.

Related

cURL in .NET application

I have a cURL command provided by WooCommerce:
curl https://example.com/wp-json/wc/v2/orders \
-u consumer_key:consumer_secret
I'm using WebClient:
using (WebClient wc = new WebClient())
{
Uri url = new Uri("https://www.myhost.com/wp-json/wc/v2/orders");
System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("consumer_key", keyValue);
byte[] responsebytes = wc.UploadValues(url, "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
}
But I'm getting this error:
IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
What have I done wrong here? I'm pretty sure my url and key are correct.
EDIT: Have just tried this as suggested by CmdrTchort and David:
using (WebClient wc = new WebClient())
{
wc.UseDefaultCredentials = true;
wc.Credentials = new NetworkCredential("consumer_key", keyValue);
string responsebody = wc.DownloadString("https://www.myhost.com/wp-json/wc/v2/orders");
}
Still receiving the same error.
EDIT: I have a suspicion I've been provided with invalid credentials I will update once this becomes clear...
I was given the wrong credentials. However that has not solved the issue.
I don't understand how consumer_key:consumer_secret is supposed to be represented in this request. There are two values: consumer_key and consumer_secret (I was only supplied with consumer_secret before, which I placed where keyValue is). I now assume that it is supposed to be of the form:
wc.Credentials = new NetworkCredential("consumer_key", "consumer_secret");
where "consumer_key" and "consumer_secret" represent the unique values provided. This does not work. This is starting to get slightly irritating.
You're posting the consumer_key:consumer_secret as part of a form POST, but that's not what cURL was doing. That looks more like a GET request with supplied authentication. Perhaps something like this:
wc.Credentials = new NetworkCredential("consumer_key", "consumer_secret");
and then making a GET request instead of a POST. With no values to upload, that part might be simplified. Maybe something like:
string responsebody = wc.DownloadString(url);
-u in curl passes the credentials as authorized headers and not as a dictionary of params.
You can add your credentials with :
wc.UseDefaultCredentials = true;
wc.Credentials = new NetworkCredential("username", "password");
Is your service responding and/or is it an untrusted or self-signed certificate?
If so , you can test ignoring the SSL-warning.
Btw, curl uses get by default (-X specifies method, which I can't see in your example) - so I'm assuming your only receiving by default and not actually posting values? If so you can use the DownloadString() directly.
So, if you're trying to get a file from this url you can do :
// IGNORE ALL SSL Certificates - would not do this in production
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(
delegate
{ return true; }
);
using (WebClient wc = new WebClient())
{
wc.UseDefaultCredentials = true;
wc.Credentials = new NetworkCredential("consumer_key", keyValue);
string responsebody = wc.DownloadString("https://www.myhost.com/wp-json/wc/v2/orders");
}

Special character in post request within c# application

I have this c# method
public void TestMethod1()
{
string login = #"partone\afif#gmail.com" ;
string pwd = "ksLLHddf5El";
var request = new RestRequest("https://secureapp4.idshost.fr/authenticationids/restloginservice.php", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Content-type", "application/json;charset=utf-8");
request.AddBody(new { authentifier = login, password = pwd });
RestClient client = new RestClient();
var response = client.Execute(request);
var data = response.Content;
}
The problem is the special character \ in the login string, it generates invalid authentifier parameter.
So I need to know how can I fix this?
The problem is likely to do with the receiving Rest endpoint.
Having looked through the RestSharp code it serializes the \ character correctly.
So when the JSON is generated it will turn your login into "partone\\afif#gmail.com" with two \\. You need to make sure the endpoint is correctly parsing this back into partone\afif#gmail.com
Its also a bit odd that the error is saying that it is an invalid parameter since you are sending it in the body.
Whats even stranger is that in your sample code you are attempting to post to a WSDL url. WSDL's are for SOAP web services and not restful webservices.

WebClient request returns empty string

In my program I need to get the content of my site, however the return of DownloadString method of the webclient object returns null, however the most intriguing is that there is no exception. the status code is 200, the request is made ​​perfectly, but the url returns an empty string.
WebClient wc = new WebClient();
String teste = wc.DownloadString("http://www.wiplay.com.br");
My site
http://www.wiplay.com.br
Seems like your website requires the user agent header to be set in order to respond.
Add the following before your call the DownloadString method:
wc.Headers.Add(HttpRequestHeader.UserAgent, "your useragent string");
In my case use of HttpClient and WebClient resulted in empty string despite status code 200 no matter what headers I set.
If somebody still suffers to this problem,using RestSharp like finally returned expected response body.
var dataString = JObject.FromObject(anonymousObject).ToString();
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddParameter("application/json", dataString, ParameterType.RequestBody);
var response = client.Post(request);

How to use RestSharp for non standard url containing symbols like = and ::?

I have to call the following URL using RestSharp.
Some part of the uri are not standard.
How can I get to use them in
The url is the following but without the white space:
http:// mysite.com/api/v2.php?method = information :: method&token=b&target_id=0
I've tried something like this but RestSharp is not calling the URL I was expecting to call.
var client2 = new RestClient("http:// mysite.com/api/v2.php");
var request = new RestRequest("method=information::method", Method.GET);
request.AddParameter("token", authenticationToken);
request.AddParameter("target_id", targetId);
You don't mention what url your code actually calls, but I guess that your method is parsed as a file/path, and not a parameter.
var client = new RestClient("http:// mysite.com/api/");
var request = new RestRequest("v2.php", Method.GET);
request.AddParameter("method", "information::method");
request.AddParameter("token", authenticationToken);
request.AddParameter("target_id", targetId);

Using Hashtable object as body/parameter for POST request (RestSharp in Xamarin Mono)

I'm having issues making POST requests with RestSharp. My Hashtable object 'param' contains key-value pairs that must be posted to the server. I've tried several combinations and have gotten weird output on the server-side.
Example 1:
var client = new RestClient();
var request = new RestRequest(url, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody (param);
Output:
Parameters: {"_json"=>[{"Key"=>"customer_subject_id", "Value"=>"300"}, {"Key"=>"client_code", "Value"=>"337"}, {"Key"=>"reservation_id", "Value"=>"9798"}, {"Key"=>"guid", "Value"=>"ODUUME4qhLmAcBVGlT4mrGbaHcbuXZID"}, {"Key"=>"customer_client_subject_id", "Value"=>"300"}, {"Key"=>"exam_code", "Value"=>"300"}, {"Key"=>"signature", "Value"=>"6bcbffb0c8ddcd89f159cf5ddd485d1eed76d1694ba329db5431f883bac3e982"}, {"Key"=>"customer_id", "Value"=>"lol"}, {"Key"=>"session_duration", "Value"=>60}]}
Example 2:
var client = new RestClient();
var request = new RestRequest(url, Method.POST);
foreach(DictionaryEntry entry in param){
request.RequestFormat = DataFormat.Json;
request.AddParameter ((entry.Key.ToString()), entry.Value);
}
Output:
Parameters: {"customer_subject_id"=>"300", "client_code"=>"337", "reservation_id"=>"9798", "guid"=>"o9LJ5e9t52xxFhxhAoHzmYd7AiQ3nu36", "customer_client_subject_id"=>"300", "exam_code"=>"300", "signature"=>"297cd7e871df885393ebe44b262cb40b8c03e55ae1f0567ff708e9811b2aedf8", "customer_id"=>"lol", "session_duration"=>"60"}
The output for #2 seems correct, but I'm getting a 401 on the server-side. Weirdly, the GET output matches that of #2, but the request is made successfully. I think the problem may be that the request, in total, is posting 10 parameters yet it should be posting one JSON formatted string in the body. Typically, I would put a JSON formatted string in the body, but even when I use a standalone JSON serializer to obtain a JSON string of the Hashtable and put in AddBody, I get the following:
Example 3:
var client = new RestClient();
var request = new RestRequest(url, Method.POST);
String paramJson = SimpleJson.SerializeObject (param);
request.RequestFormat = DataFormat.Json;
request.AddBody (paramJson);
Output:
Parameters: {"_json"=>"[{\"Key\":\"customer_subject_id\",\"Value\":\"300\"},{\"Key\":\"client_code\",\"Value\":\"337\"},{\"Key\":\"reservation_id\",\"Value\":\"9798\"},{\"Key\":\"guid\",\"Value\":\"56ZAsFtBx7jhDmdconWTb40qGirNagxK\"},{\"Key\":\"customer_client_subject_id\",\"Value\":\"300\"},{\"Key\":\"exam_code\",\"Value\":\"300\"},{\"Key\":\"signature\",\"Value\":\"57d7c878dec24da98815071d1dc3730873285b3ae65f9d98591da94266b8f7d7\"},{\"Key\":\"customer_id\",\"Value\":\"lol\"},{\"Key\":\"session_duration\",\"Value\":60}]"}
I'm mostly curious as to why the JSON string that RestSharp is creating contains "_json" at the beginning of it.
Thanks,
John
Is your server running Rails? Maybe this is relevant https://groups.google.com/forum/#!topic/rubyonrails-core/ZYBI_XHYpak
If you have control of the server side, might be better to use AddParameter and pass a JSON string, which you can parse on the server side.

Categories