Please refer to the below code. How can I test/debug, whether the below code worked correctly or not. It runs and there are no compilation/runtime errors.
The end result of the below code is to set one of the controls in the page, to hold the POST data from below code. However I haven't come that far yet.
protected override void OnInit(EventArgs e)
{
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "http://s.com/is/image/scom/2Peel";
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://m.com/Confirm.aspx?ID=175");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
}
Update 1: I tried to find out the response using below code, but the page doesn't load at all.
HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
Console.WriteLine("Content length is {0}", response.ContentLength);
Console.WriteLine("Content type is {0}", response.ContentType);
Use the GetResponse method of your HttpWebRequest object (which you named "myRequest").
Related
I just can't seem to be able to post a JSON to the webpage https://authserver.mojang.com/authenticate and get a response.
when I post the JSON it just says
The remote server returned an error: (400) Bad Request
I've gone through many different scripts by others and created my own by converting the Java code to C#. Anyway, here's the code that has worked the best so far.
string authserver = "https://authserver.mojang.com/authenticate";
byte[] rawData = fs.GetBytes(**[JSON]**);
WebRequest request = WebRequest.Create(authserver);
request.ContentType = "application/json";
request.Method = "POST";
//request.ContentLength = rawData.LongLength;
WebResponse connection = request.GetResponse();
connection.ContentType = "application/json";
connection.ContentLength = rawData.LongLength;
Stream stream = connection.GetResponseStream();
stream.Write(rawData, 0, rawData.Length);
stream.Flush();
byte[] rawVerification = new byte[10000];
int count = stream.Read(rawVerification, 0, 10000);
Edit:
is it possible to do this code with webclient?
Edit:
it had an invalid input, the json didn't have the correct data needed
try this:
WebRequest request = WebRequest.Create (authserver);
request.Method = "POST";
string postData = "YourJSON";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
using(Stream s = request.GetRequestStream ()){
s.Write (byteArray, 0, byteArray.Length);
}
WebResponse response = request.GetResponse ();
using(var dataStream = response.GetResponseStream ()){
using(StreamReader reader = new StreamReader (dataStream)){
string responseFromServer = reader.ReadToEnd ();
}
}
response.Close();
Essentially You shouldn't call getResponse() before you submit your data
I've always done my web services in PHP. Now I'm trying some ASP.NET on a project and I found myself on a tricky situation. I have the following C# code, behaving as a "client"
public void sendRequest(string URL, string JSON)
{
ASCIIEncoding Encode = new ASCIIEncoding();
byte[] data = Encode.GetBytes(JSON);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookieContainer;
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
WebHeaderCollection header = response.Headers;
var encoding = ASCIIEncoding.ASCII;
string responseText;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
responseText = reader.ReadToEnd();
}
returnRequestTxtBx.Text = responseText;
}
Well, now I want to handle on the ASPX.CS side...
my question is... how do I access the data I sent as a POST?
Is there a way in the "Page_Load" method that I can handle the JSON I sent?
To read post method data on your server side read HttpContext.Request.Form method:
protected void Page_Load(object sender, EventArgs e)
{
string value=Request.Form["keyName"];
}
Or if you want to access row body data simply read: Request.InputStream.
And if you want handle Json format consider Newtonsoft.Json packege.
I have problem with post JSON with authentication/Authorization.. Below is my code.. opponent said that they didnt receive the header...and i have no idea why...
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(stringData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(serverURL);
req.Method = "POST";
req.ContentType = "application/json";
req.ContentLength = data.Length;
req.Headers.Add("Authentication", merchantID);
req.Headers["Authentication"] = merchantID;
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string returnString = response.StatusCode.ToString();
i am writing some example code to attach header while you calling service...
hope it is needful...
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(stringData);
HttpWebRequest reqest = (HttpWebRequest)WebRequest.Create(serviceUri);
reqest.Headers.Add(LoginName,LoginName);
reqest.Headers.Add(AuthenticationKey,AuthenticationKey);
reqest.Headers.Add(SessionKey,SessionKey);
reqest.ContentType = "application/json";
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string returnString = response.StatusCode.ToString();
I cannot surely say where the problem is. It can be even on a server-side.
Recently I worked on a project with header authentication and I have noticed an interesting thing. My PHP server received these headers with 'HTTP_' prefix.
In other words, I was making a request like:
req.Headers.Add("Authentication", merchantID);
And received it on server this way:
echo $_SERVER['HTTP_Authentication'];
I have spent a bunch of time to find it out.
You, actually, can ask your opponent if any similar header is present or ask him to examine your requests better and give you a feedback.
Also, try using WebClient. Maybe, it will help.
Furthermore, it is much more convenient.
string data = "{\"a\": \"b\"}";
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Authentication", merchantID);
var result = client.UploadString(serverURL, "POST", data);
I have this php code in server :
foreach($_POST as $pdata)
echo " *-* ". $pdata." *-*<br> ";
and i am sending post data by httpwebrequest in c# :
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://127.0.0.1/22") as HttpWebRequest;
//Specifing the Method
httpWebRequest.Method = "POST";
//Data to Post to the Page, itis key value pairs; separated by "&"
string data = "Username=username&password=password";
//Setting the content type, it is required, otherwise it will not work.
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
//Getting the request stream and writing the post data
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(data);
}
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
static html codes of php page are shown.
but nothing of posted value are shown in messagebox .that means no data are posted.
what is wrong?
You need to get the bytes of the data.
Try this code, from this guy's blog post.
public string Post(string url, string data) {
string vystup = null;
try
{
//Our postvars
byte[] buffer = Encoding.ASCII.GetBytes(data);
//Initialisation, we use localhost, change if appliable
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
//Our method is post, otherwise the buffer (postvars) would be useless
WebReq.Method = "POST";
//We use form contentType, for the postvars.
WebReq.ContentType = "application/x-www-form-urlencoded";
//The length of the buffer (postvars) is used as contentlength.
WebReq.ContentLength = buffer.Length;
//We open a stream for writing the postvars
Stream PostData = WebReq.GetRequestStream();
//Now we write, and afterwards, we close. Closing is always important!
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
//Get the response handle, we have no true response yet!
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Let's show some information about the response
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
vystup = _Answer.ReadToEnd();
//Congratulations, you just requested your first POST page, you
//can now start logging into most login forms, with your application
//Or other examples.
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return vystup.Trim()+"\n";
}
I'm trying to send a file in chunks to an HttpHandler but when I receive the request in the HttpContext, the inputStream is empty.
So a: while sending I'm not sure if my HttpWebRequest is valid
and b: while receiving I'm not sure how to retrieve the stream in the HttpContext
Any help greatly appreciated!
This how I make my request from client code:
private void Post(byte[] bytes)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost:2977/Upload");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.SendChunked = true;
req.Timeout = 400000;
req.ContentLength = bytes.Length;
req.KeepAlive = true;
using (Stream s = req.GetRequestStream())
{
s.Write(bytes, 0, bytes.Length);
s.Close();
}
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
}
this is how I handle the request in the HttpHandler:
public void ProcessRequest(HttpContext context)
{
Stream chunk = context.Request.InputStream; //it's empty!
FileStream output = new FileStream("C:\\Temp\\myTempFile.tmp", FileMode.Append);
//simple method to append each chunk to the temp file
CopyStream(chunk, output);
}
I suspect it might be confusing that you are uploading it as form-encoded. but that isn't what you are sending (unless you're glossing over something). Is that MIME type really correct?
How big is the data? Do you need chunked upload? Some servers might not like this in a single request; I'd be tempted to use multiple simple requests via WebClient.UploadData.
i was trying the same idea and was successfull in sending file through Post httpwebrequest. Please see the following code sample
private void ChunkRequest(string fileName,byte[] buffer)
{
//Request url, Method=post Length and data.
string requestURL = "http://localhost:63654/hello.ashx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Chunk(buffer) is converted to Base64 string that will be convert to Bytes on the handler.
string requestParameters = #"fileName=" + fileName +
"&data=" + HttpUtility.UrlEncode( Convert.ToBase64String(buffer) );
// finally whole request will be converted to bytes that will be transferred to HttpHandler
byte[] byteData = Encoding.UTF8.GetBytes(requestParameters);
request.ContentLength = byteData.Length;
Stream writer = request.GetRequestStream();
writer.Write(byteData, 0, byteData.Length);
writer.Close();
// here we will receive the response from HttpHandler
StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream());
string strResponse = stIn.ReadToEnd();
stIn.Close();
}
I have blogged about it, you see the whole HttpHandler/HttpWebRequest post here
http://aspilham.blogspot.com/2011/03/file-uploading-in-chunks-using.html
I hope this will help