I have spent ages trying various different ways to convert this curl to c#. Could someone please help.
I am trying to do a http post and keep getting error 500.
here is what I want to convert:
curl --user username:password -X POST -d "browser=Win7x64-C1|Chrome32|1024x768&url=http://www.google.com" http://crossbrowsertesting.com/api/v3/livetests/
and this is what I have so far:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseurl);
request.Method = "POST";
request.Accept = "application/json";
request.Credentials = new NetworkCredential(username, password);
var response = request.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
values.Add(text);
}
Tried this method too but it didn't work:
List<string> data = new List<string>();
data.Add("browser=Win7x64-C1|Chrome20|1024x768");
data.Add("url=URL");
data.Add("format=json");
data.Add("callback=doit");
var request = WebRequest.Create("CrossBrowserTestingURL");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = new NetworkCredential(username, password);
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write("data=" + data);
}
var response = request.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
values.Add(text);
}
I modified the first one to write data to the request stream as per http://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx, does this work:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseurl);
request.Method = "POST";
request.Accept = "application/json";
request.Credentials = new NetworkCredential(username, password);
request.UserAgent = "curl/7.37.0";
request.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string data = "browser=Win7x64-C1|Chrome32|1024x768&url=http://www.google.com";
streamWriter.Write(data);
}
var response = request.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
values.Add(text);
}
Just implemented an experimental ASP.NET Core app that turns curl commands into C# code using Roslyn
Give it a try, please:
https://curl.olsh.me/
You can paste your command into curlconverter.com/csharp/ and it will convert it into this code using HttpClient:
using System.Net.Http.Headers;
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://crossbrowsertesting.com/api/v3/livetests/");
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("username:password")));
request.Content = new StringContent("browser=Win7x64-C1|Chrome32|1024x768&url=http://www.google.com");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Related
I have been trying to get an API response from a url that requires a basic authorization including username and password along with clientid in the header as I am getting response from API if I call it in Postman. I want to try the same thing in my asp.net c# project. But always get error 400 Bad request.
Here is my code;
NetworkCredential networkCredential = new NetworkCredential(UserName, Password);
CredentialCache myCredentialCache = new CredentialCache { { new Uri(url4), "Basic", networkCredential } };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url4);
UTF8Encoding encoding = new UTF8Encoding();
request.Method = WebRequestMethods.Http.Get;
request.PreAuthenticate = true;
request.Credentials = myCredentialCache;
using (WebResponse response = request.GetResponse()) //This is where I get error Bad request
{
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
using (Stream dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(dataStream))
{
// StreamReader sr = new StreamReader(stream);
string strResult = reader.ReadToEnd();
for (int i = 0; i < strResult.Length; i++)
{
if (strResult.Contains(getValue) == true)
{
Label1.Text = strResult;
}
else
{
//error
}
}
reader.Close();
}
}
}
Can anyone help me?
Plaese check it :
Uri requestUri = null;
Uri.TryCreate((linkUrl), UriKind.Absolute, out requestUri);
NetworkCredential nc = new NetworkCredential(username, password);
CredentialCache cache = new CredentialCache();
cache.Add(requestUri, "Basic", nc);
cache.Add(new Uri(linkUrl), "NTLM", new NetworkCredential("", ""));
// Requesting query string
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
request.Credentials = cache;
// Getting response from WebRequest
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader respStream = new StreamReader(response.GetResponseStream());
Following is the API Call i make using postman and get a ticket back in the response body (screenshot):
I am not able to get the ticket in a HttpWebRequest Response in C#. Please below see the small sample code:
C# code
HttpWebRequest Request = WebRequest.Create(strUrl) as HttpWebRequest;
Request.Method = "POST";
Request.Headers.Add("Authorization", "Basic <>");
//Request.ContentType = "application/form-data";
Request.KeepAlive = true;
string data = string.Format("username=" + UserName + "&password=" + Password);
byte[] dataStream = Encoding.UTF8.GetBytes(data);
Request.ContentLength = dataStream.Length;
using (Stream newStream = Request.GetRequestStream())
{
// Send the data.
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
}
var Response = (HttpWebResponse)Request.GetResponse();
using (var stream = Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
if (Response.StatusCode != HttpStatusCode.OK)
throw new Exception("The request did not complete successfully and returned status code " + Response.StatusCode);
ResponseTicket strTicket= JsonConvert.DeserializeObject<ResponseTicket>(reader.ToString());
JsonConvert.DeserializeObject(Response.GetResponseStream().ToString());
MessageBox.Show(strTicket.Ticket);
}
Where as statuscode=200. But the content length is 0.
It is very difficult to find any meaning full help on CS10.5 API. I have checked there AppWorks platform but in vain. Would appreciate if someone can find the problem in the code, which apparently i can not see.
I don't know if this is still an issue for you. For me it was also, but figured it out:
public string LoginAsAdminAndRetrieveTicket(string userName, string passWord, string domain, string url)
{
var uri = $"http://{url}/otcs/llisapi.dll/api/v1/auth";
var request = new HttpRequestMessage();
request.Headers.Add("Connection", new[] { "Keep-Alive" });
request.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
request.Headers.Add("Pragma", "no-cache");
request.RequestUri = new Uri(uri);
request.Method = HttpMethod.Post;
request.Content = new StringContent($"username={userName};password={passWord}", Encoding.UTF8, "application/x-www-form-urlencoded");
var httpClientHandler = new HttpClientHandler
{
Proxy = WebRequest.GetSystemWebProxy(),
UseProxy = true,
AllowAutoRedirect = true
};
using (var client = new HttpClient(httpClientHandler))
{
var response = client.SendAsync(request).Result;
string ticket;
var vals = response.Headers.TryGetValues("OTCSTicket", out IEnumerable<string> temp) ? temp : new List<string>();
if (vals.Any())
{
ticket = vals.First();
}
return response.Content.ReadAsStringAsync().Result;
}
}
So for example: https://www.website.com/index.php?action=get_products
This page/action has the following source code: <tr><td>Table</td></tr>
The index.php page has the following source code: <body>Hello</body>
When I use the following code I still get the index.php code and not the action page code:
Uri url = new Uri("https://www.website.com/index.php");
HttpWebRequest request = null;
ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
CookieContainer cookieJar = new CookieContainer();
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookieJar;
request.Method = "GET";
HttpStatusCode responseStatus;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
responseStatus = response.StatusCode;
url = request.Address;
}
if (responseStatus == HttpStatusCode.OK)
{
UriBuilder urlBuilder = new UriBuilder(url);
urlBuilder.Path = urlBuilder.Path.Remove(urlBuilder.Path.LastIndexOf('/')) + "/j_security_check";
request = (HttpWebRequest)WebRequest.Create(urlBuilder.ToString());
request.Referer = url.ToString();
request.CookieContainer = cookieJar;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(requestStream, Encoding.ASCII))
{
string postData = "?action=get_products";
requestWriter.Write(postData);
}
string responseContent = null;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader responseReader = new StreamReader(responseStream))
{
responseContent = responseReader.ReadToEnd();
}
Console.WriteLine(responseContent);
}
else
{
Console.WriteLine("Client was unable to connect!");
}
I found the code above in another stackoverflow thread. The problem is I have to login first with username user and password pass. How do I get this done using C#?
I'm trying to send a test notification to my ipod via UrbanAirship with C#. I've tried many code snippets trying to send my notification to UrbanAirship from my Windows server, yet I always end up with a 401 error.
Here's my latest code:
string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\""+ devToken +"\"]}";
var uri = new Uri("https://go.urbanairship.com/api/push/");
var encoding = new UTF8Encoding();
var request = (HttpWebRequest)WebRequest.Create(uri);
char[] charArray = Encoding.UTF8.GetChars(Encoding.UTF8.GetBytes(postData));
request.Method = "POST";
request.Credentials = new NetworkCredential(username, password);
request.ContentType = "application/json";
request.ContentLength = encoding.GetByteCount(charArray);
using (var stream = request.GetRequestStream())
{
stream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
stream.Close();
var response = request.GetResponse();
response.Close();
}
Note: I've verified that my username and password are correct.
===UPDATE===
I would say that there's something woring with my urbanairship config or so but the following worked:
curl -X PUT -u "appKey:appSecret" -H "Content-Type: application/json" --data '{"alias": "myalias"}' https://go.urbanairship.com/api/device_tokens/myTOken/
Fixed, I've modified my code and most important: YOUR PASSWORD IS THE APPLICATION MASTER SECRET
string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\""+ devToken +"\"]}";
var uri = new Uri("https://go.urbanairship.com/api/push/");
var encoding = new UTF8Encoding();
var request = (HttpWebRequest)WebRequest.Create(uri);
char[] charArray = Encoding.UTF8.GetChars(Encoding.UTF8.GetBytes(postData));
request.Method = "POST";
request.Credentials = new NetworkCredential(username, password);
request.ContentType = "application/json";
request.ContentLength = encoding.GetByteCount(charArray);
using (var stream = request.GetRequestStream())
{
stream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
stream.Close();
var response = request.GetResponse();
response.Close();
}
Here is my code:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/jsonrpc.cgi");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "someParameters";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}
string Bugzilla_logincookie= httpResponse.Headers.ToString();
Bugzilla_logincookie= Bugzilla_logincookie.Substring(plsWork .IndexOf("logincookie") + 12);
Bugzilla_logincookie= Bugzilla_logincookie.Substring(0, plsWork .IndexOf(";"));
CookieContainer cc = new CookieContainer();
cc.SetCookies(new Uri("http://localhost"), Bugzilla_logincookie);
var httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/jsonrpc.cgi");
httpWebRequest2.ContentType = "application/json";
httpWebRequest2.Method = "POST";
httpWebRequest2.Proxy.Credentials = new NetworkCredential("username", "password");
httpWebRequest2.CookieContainer = cc;
using (var streamWriter2 = new StreamWriter(httpWebRequest2.GetRequestStream()))
{
string json = "someParametersForJsonCall";
streamWriter2.Write(json);
}
var httpResponse2 = (HttpWebResponse)httpWebRequest2.GetResponse();
using (var streamReader2 = new StreamReader(httpResponse2.GetResponseStream()))
{
var responseText = streamReader2.ReadToEnd();
}
I have problem with using proxy. The thing I'm trying to do is: use a Proxy for http://www.bugzilla.org/docs/tip/en/html/api/Bugzilla/WebService/User.html to call the login method and then store cookies of response and send them with each call of the session.
I get this error:
"You must log in before using this part of Bugzilla."
What am I mistakenly using?