HttpWebRequest with proxy - setting cookies - c#

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?

Related

How to pass data.bind in POST request using C#

i have a web app connected with crm Dynamics 365. I want to create record in an entity using API, but the entity has lookup fields to another entities. I tried this code but it gives bad request error. How can i send the values of the lookup fields in the API?
JSON:{
"msdyn_name": "Asset",
"msdyn_account#odata.bind": "/accounts(7f7e031b-0e20-ea11-a810-000d3a2d54fd)",
"new_externalproj#odata.bind": "/msdynce_externalprojects(ee3f03c6-751f-ea11-a810-000d3a27b751)" }
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new
{
msdyn_name = "Asset",
msdyn_account = "7f7e031b-0e20-ea11-a810-000d3a2d54fd",
new_externalproj = "ee3f03c6-751f-ea11-a810-000d3a27b751"
});
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://XXX.dynamics.com/api/data/v9.1/msdyn_customerassets");
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", String.Format("Bearer {0}", result.AccessToken));
httpWebRequest.Headers.Add("OData-MaxVersion", "4.0");
httpWebRequest.Headers.Add("OData-Version", "4.0");
httpWebRequest.ContentType = "application/json";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}

delete a Firebase user using C#

Is it possible to delete a user account in Firebase in C#?
I can successfully create users but on the delete, I get INSUFFICIENT_PERMISSION bu I don't know how to provide the correct permissions.
The code for creating a user:
var httpWebRequest = (HttpWebRequest)WebRequest.Create(NEW_USER_URL);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var body = new
{
email = email,
password = password
};
string json = JObject.FromObject(body).ToString();
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
The code for deleting a user:
var httpWebRequest = (HttpWebRequest)WebRequest.Create(DELETE_USER_URL);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var body = new
{
localId = uUid
};
string json = JObject.FromObject(body).ToString();
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
The urls:
static string NEW_USER_URL = $#"https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key={ConfigurationManager.AppSettings["FireBaseProjectApiKey"]}";
static string DELETE_USER_URL = $#"https://www.googleapis.com/identitytoolkit/v3/relyingparty/deleteAccount?key={ConfigurationManager.AppSettings["FireBaseProjectApiKey"]}";

How can i post json with cookies to server with c# webrequest?

I'm new in c# ,and want to send json post to server with this code:
var httpWebReques = (HttpWebRequest) WebRequest.Create(#"http://myDomain/api/FileCommand/AddGig ");
httpWebReques.ContentType = "application/json";
httpWebReques.Method = "POST";
using (var streamWriter=new StreamWriter(httpWebReques.GetRequestStream()))
{
JObject obj = JObject.FromObject(new
{
PhoneNumber= phoneNumber,
TrafficGigCount="1",
PaymentAmountRial="2000",
PaymentTrackingNo="123434"
});
string json = obj.ToString(); //"{\"PhoneNumber\":\""+phoneNumber+"\"," + "\"TrafficGigCount\":\"1\","+ "\"PaymentAmountRial\":\"1000\","+ "\"PaymentTrackingNo\":\"1254\"}";
streamWriter.Write(obj);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse) httpWebReques.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
every thing is ok and now want to send server cookie with this code:
httpWebReques.CookieContainer = new CookieContainer();
httpWebReques.CookieContainer.SetCookies(new Uri("http://www.tclnet.ir/"), cookies);
for that purpose write this code:<br/>
var httpWebReques = (HttpWebRequest) WebRequest.Create(#"http://www.tclnet.ir/api/FileCommand/AddGig ");
httpWebReques.ContentType = "application/json";
httpWebReques.Method = "POST";
httpWebReques.CookieContainer = new CookieContainer();
httpWebReques.CookieContainer.SetCookies(new Uri("http://www.tclnet.ir/"), cookies);
using (var streamWriter=new StreamWriter(httpWebReques.GetRequestStream()))
...
but when receive to this line:
var httpResponse = (HttpWebResponse) httpWebReques.GetResponse();
get this error:
The remote server returned an error: (500) Internal Server Error.
How can i solve that?thanks.
my error:

Convert CURL to C#

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();

Programmatically logging in to a website

How does one log in to a website programmatically?
I just want to check that the provided username and password of a website is correct or not.
Thanks.
The easiest way to do this from .NET is Watin. You would do something like:
using (var browser = new IE("http://mysite.com"))
{
browser.TextField(Find.ByName("email")).TypeText("my#email.com");
browser.TextField(Find.ByName("password")).TypeText("password");
browser.Button(Find.ByName("login")).Click();
if (browser.ContainsText("Welcome my#email.com!"))
{
// Success
}
}
To do it with HttpWebRequest, you would:
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentLength = postContent.Length;
req.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
streamWriter.Write(postContent);
}
using (var res = (HttpWebResponse)req.GetResponse())
{
_status = res.StatusCode;
using (var streamReader = new StreamReader(res.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
}
Just to add a 3rd way, you could also use WebClient:
var nvc = new NameValueCollection();
nvc.Add("email", "my#email.com");
nvc.Add("password", "password");
var wc = new WebClient();
byte[] responseArray = wc.UploadValues("http://mysite.com",nvc);
string responseText = Encoding.ASCII.GetString(responseArray));

Categories

Resources