C# Http Request with username - c#

Hello everyone I am currently working on a Post Method of my C# work. As the URL I am going to send request to requires username and password, I have it but I do not know how to include them in my code. How should I insert them into my code?
Here is my request:
Content-Type: multipart/related; boundary="myboundary"
From: 12345678
To: 12345678
Password: my_Password
Username: my_UserName
--myboundary
Content-Type: application/smil
Content-ID: <abc.smil>
Content-Location: abc.smil
Here are my code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://myurl.com");
request.Method = "POST";
request.ContentType = "multipart/related; boundary = myboundary";
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);

Related

How to create a request that looks like this

I need to replicate a HTTP request using C# and the HttpWebRequest, that looks like this:
HEADER: POST /upnp/control/x_contact HTTP/1.1 Host: fritz.box:49000
Connection: Keep-Alive User-Agent:...
So far I got everything working, except for the part after the POST
"/upnp/control/x_contact HTTP/1.1".
How would I have to modify the HttpWebRequest to get these additional data to the server?
PS: This is how the java code looks, that generates the correct request. I would like to port this code to C# and send the same request from there:
socket = new Socket(InetAddress.getByName("fritz.box"), 49000);
// Send header
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));
writer.write("POST /igdupnp/control/WANIPConn1 HTTP/1.1");
writer.write("Host: fritz.box:49000\r\n");
writer.write("SOAPACTION: \"urn:schemas-upnp-org:service:WANIPConnection:1#GetStatusInfo\"\r\n");
writer.write("Content-Type: text/xml; charset=\"utf-8\""+"\r\n");
writer.write("Content-Length: " + myData.length() + "\r\n");
writer.write("\r\n");
// Send data
writer.write(myData);
writer.flush();
And this is my C# code so far (producing an incomplete HTML request):
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (#"http://fritz.box:49000");
webRequest.Headers.Add ("SOAPACTION", "urn:schemas-upnp-org:service:WANIPConnection:1#GetStatusInfo");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";

HttpWebRequest and Cookie handling

Sending cookie received from httpwebrequest is not giving correct result however if i copy paste cookie value from browser cookie than it returns correct result. why i am not getting result from httpwebrequest but works perfectly fine from browser?
CookieContainer cookieContainer = new CookieContainer();
var targetUri = new Uri("URL1");
HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(targetUri);
myHttpWebRequest.Method = "GET";
myHttpWebRequest.CookieContainer = cookieContainer;
//Get Response
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
//Create Request
targetUri = new Uri("URL2");
myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(targetUri);
myHttpWebRequest.Method = "GET";
myHttpWebRequest.CookieContainer = cookieContainer;
//Get Response
myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
using (StreamReader reader = new StreamReader(myHttpWebResponse.GetResponseStream()))
{
string html = reader.ReadToEnd();
}
Following is second request(URL2) fiddler with cookie received through first request(URL1):
Request:
GET URL2
HTTP/1.1
Host: www.xyz.com
Cookie: JSESSIONID=Mn7qJwrRnxLn1NNfT1PNr1L2Gr2KCkfFVCRS1wfsT4zfzWJhT62J!-876337174
Response:
HTTP/1.1 200 OK
Date: Fri, 27 Feb 2015 13:03:52 GMT
Content-Length: 13
Content-Type: text/html;charset=UTF-8
X-Powered-By: Servlet/2.5 JSP/2.1
Now if i copy paste first url(URL1) in browser and use cookie value from browser then it returns correct result:
Request:
GET URL2
HTTP/1.1
Host: www.xyz.com
Cookie: JSESSIONID=PPPHJwmKQNh2ykVXytlcfTDH2YWNbtv76vPBzZTG3Dfdm9Mx0J74!-876337174
Response:
HTTP/1.1 200 OK
Date: Fri, 27 Feb 2015 13:06:15 GMT
Content-Type: text/html;charset=UTF-8
X-Powered-By: Servlet/2.5 JSP/2.1
Content-Length: 21417
Weblogic is returning the cookies in the response, and you need to send it back in the next request.
cookieContainer.Add(response.Cookies);
(Your cookieContainer is on your machine and is empty).

C# WebRequest POST returns 500 internal server error

I want to submit xml via postbody to a web service, but am getting a 500 Error from the GetResponse() method.
Here is my snippet:
WebRequest request = WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/xml";
request.Credentials = new NetworkCredential("UserName", "Pass", "Domain");
byte[] body= Encoding.UTF8.GetBytes(myXML);
request.ContentLength = body.Length;
request.GetRequestStream().Write(body, 0, body.Length);
WebResponse response = request.GetResponse(); //500 response
Does anyone know why the server is responding with this error? Am I providing all the needed headers? I have confirmed that the service works through a REST Client Console, but can't seem to POST to it via code.
I had to set request.ContentType = "application/x-www-form-urlencoded" instead of request.ContentType = "application/xml" for it to correctly POST the xml data in the request. If anyone out there has a the technical explanation as to why application/x-www-form-urlencoded worked instead of application/xml, I would love to hear it.

Malformed string exception while sending "&" in Json to AppEngine

I am trying to send Facebook graph link to the AppEngine server. I receive "Malformed string exception". Here is my method sending json to server:
public async Task<string> SendJSONData(string urlToCall, string JSONData)
{
// server to POST to
string url = urlToCall;
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
//create some json string
string json = "action=" + JSONData;
// convert json to byte array
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);
// Write the bytes to the stream
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}
WebResponse response = await httpWebRequest.GetResponseAsync();
StreamReader requestReader = new StreamReader(response.GetResponseStream());
String webResponse = requestReader.ReadToEnd();
return webResponse; }
Here is what I sniff using Fiddler:
POST http://x.appspot.com/register HTTP/1.1
Accept: */*
Content-Length: 376
Accept-Encoding: identity
Content-Type: application/x-www-form-urlencoded
User-Agent: NativeHost
Host: x.appspot.com
Connection: Keep-Alive
Pragma: no-cache
action={
"mailFb": "mail#gmail.com",
"userName": "Michael",
"userSurname": "w00t",
"nickname": "Michael w00t",
"userSex": "male",
"userAvatar": "https://graph.facebook.com/myperfectid/picture?type=large&access_token=BlahblahblahblahToken"
}
So everything looks fine, but the problem is that i receive the following error in AppEngine log:
2013-03-02 17:52:10.431 /register 500 56ms 0kb NativeHost
W 2013-03-02 17:52:10.427 /register com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated string at line 7 column 79 at com.google.g
C 2013-03-02 17:52:10.429 Uncaught exception from servlet com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated string at line 7 colu
I managed to narrow the problem to its source, which is "&" character. So my question is, how to fix the code, so that it works with AppEngine.
Oh, here is how i read the received data on the server:
gson.fromJson(reader, User.class);
The problem is highlighted by the fact you're claiming you are sending "Content-Type: application/x-www-form-urlencoded"
But it isn't. Hence the error.
The correct encoding for & is &.

.NET C# using HTTPrequest similar to Curl script

I´m using .NET C# and want to use HTTPrequest to make a POST in the same way as it is written in Curl:
curl
--header ’Accept: text/html’
--user ’test1:password’
--Form ’wait=0’
--Form ’data=#data.csv;type=text/csv’
some URL address here
I´m getting Error 500 Internal error from the Internet server.
The data to be send is a CSV file.
My source code in C#:
string data = "Time, A, B\n20120101, 100, 24\n20120102\n, 101, 27";
// Create a request using a URL that can receive a post.
request = WebRequest.Create(url);
//Set authorization
request.Credentials = new NetworkCredential(username, password);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(data);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the original response.
WebResponse response = request.GetResponse();
this.Status = ((HttpWebResponse)response).StatusDescription;
// Get the stream containing all content returned by the requested server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content fully up to the end.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
What am I doing wrong?
cURL uses the multipart/form-data content type to create its requests. I think this is required in your case as you are passing both a text parameter and a file. Sadly the .Net framework does not appear to have built in support for creating this content type.
There is a question on SO that gives example code for how to do it yourself here: Multipart forms from C# client
For reference the HTTP request generated by that cURL command looks something like this:
POST http://www.example.com/example HTTP/1.1
Authorization: Basic J3Rlc3Q6cGFzc3dvcmQn
User-Agent: curl/7.33.0
Host: www.example.com
Accept: text/html
Connection: Keep-Alive
Content-Length: 335
Expect: 100-continue
Content-Type: multipart/form-data; boundary=------------------------99aa46d554951aa6
--------------------------99aa46d554951aa6
Content-Disposition: form-data; name="'wait"
0'
--------------------------99aa46d554951aa6
Content-Disposition: form-data; name="'data"; filename="data.csv"
Content-Type: text/csv'
Time, A, B\n20120101, 100, 24\n20120102\n, 101, 27
--------------------------99aa46d554951aa6--
Doesn't data need to be URL encoded for a form post? http://en.wikipedia.org/wiki/POST_%28HTTP%29#Use_for_submitting_web_forms

Categories