Wonder if someone could assist me please, what I'm trying to achieve is to send data from one site to another: So in my 'sending' site I have a page that that runs the following:
string message;
message = "DATA DATA DATA DATA!!!";
System.Net.WebRequest request = WebRequest.Create("http://clt-umbraco.test.clt.co.uk/storereceive/?data-response");
request.ContentType = "application/json";
request.Method = "POST";
request.Headers["X-Parse-Application-Id"] = "aaaaaaaaaaaaaaa";
request.Headers["X-Parse-REST-API-Key"] = "bbbbbbbbbbbbbbb";
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("{\"channels\": [\"\"], \"data\": { \"alert\": \" " + message + "\" } }");
string result = System.Convert.ToBase64String(buffer);
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
WebResponse response = request.GetResponse();
//jsonString.Text = response;
reqstr = response.GetResponseStream();
StreamReader reader = new StreamReader(reqstr);
jsonString.Text = reader.ReadToEnd();
And on my receiving site/page I have the following on page load:
string[] keys = Request.Form.AllKeys;
for (int i = 0; i < keys.Length; i++)
{
Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}
I can see that this page load event is firing but the Request.Form.Allkeys object is empty where I would hope it would contain the data from the sending page. Obviously I'm going drastically wrong somewhere....could someone help please??
Thanks,
Craig
That is because You are not posting a form, you are uploading raw data.
Set
request.ContentType="application/x-www-form-urlencoded";
And populate your post data as such:
Key1=value1&key2=value2
You should also consider encoding the values with HttpServerUtility.UrlEncode
If you still wan't to send raw data though, then at the server end, you should read the incoming data like: (instead of Request.Form[])
byte[] requestRawData = Request.BinaryRead(Request.ContentLength);
Related
I want to send some json data using this code to a distant server (Rest, outside my control), following the way I'm sending it :
I create the url and the request method first :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(gUrlDot);
request.Method = "POST";
Dictionary<String, String> lDictionary = new Dictionary<String, String>();
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Dot lDot= new Dot();
serviceContext lserviceContext = new serviceContext();
items litems = new items();
lDot.rad = pClient;
lDictionary.Add("companyId", "00230");
lDictionary.Add("treatmentDate", lGlobals.FormatDateYYYYMMDD());
lDictionary.Add("country", "FR");
lDictionary.Add("language", "fr");
lDictionary.Add("Id", "test");
litems.contextItem = lDictionary;
lDot.serviceContext = lserviceContext;
lDot.serviceContext.items = litems;
String Input=_Tools.JsonSerializer(lDot);
log.Debug("Input Dot " + Input);
Byte[] byteArray = encoding.GetBytes(Input);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
When i'm getting here it crashes with an execption : Error 500 !
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
string output = response.ToString();
lTrace.AppendLine("-Flux Json recu => " + response.StatusCode + " " + length);
log.Debug("Output Dot " + output);
}
log.Info(LogsHelper.LogHeader("End processing Get list ", pClient, Service.SrvGetList, "", lResponse.StatusCode, lResponse.StatusLabel, lResponse.ResponseObject, ref lTrace));
}
catch (Exception ex)
{
lResponse.StatusCode = StatusCodes.ERROR_COMMUNICATION;
log.Error(LogsHelper.LogHeader("End processing Get list", pClient, Service.SrvGetList, "", lResponse.StatusCode, ex.Message, lResponse.ResponseObject, ref lTrace));
}
return lResponse;
}
what am i missing here?
A 500 error means there's a problem on the server you're making the request to. You'll need to check to make sure two things;
1) Make sure your request is properly formatted, and doesn't have any surprises or invalid values for the requested resource.
2) that the server you want to talk to CAN get requests, and that its up-to-date (if you control the client).
In either case, the most common reason for a 500 is that something outside of your control has gone wrong on the client server.
I'm using C# in send POST data to some page ! It's Really Work ...
I want Ask how i can work with Result data (GET)...
I want know if Results have redirect to Another page ....
string Uname = username.Text;
string Pass = (item.Text);
ASCIIEncoding encoding = new ASCIIEncoding();
string pastData = POST1.Text + "=" + Uname + "&" + POST2.Text + "=" + Pass + "&" + Subtxt.Text;
// MessageBox.Show(pastData);
byte[] data = encoding.GetBytes(pastData);
WebRequest requst = WebRequest.Create(url.Text);
requst.Method = "POST";
requst.ContentType = "application/x-www-form-urlencoded";
requst.ContentLength = data.Length;
Stream stream = requst.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = requst.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
MessageBox.Show(sr.ReadToEnd());
This Code is work to Send POST Without problem
I Want know if sr value have redirect to another page ...
I have some Idea .. i'm Search For redirect word in sr ..
Some website not found redirect word on back Data(GET) .. but it redirect ...
**Conclusion : **
if i have admin page website ... I'm send POST with true Data .. i Want know if it Result redirect to page admin Manager
I think you want to set AllowAutoRedirect to false on the request (you will need to cast it to HttpWebRequest). Then you can inspect the response code and see if it is a redirect. The redirected target page should be in the Location header.
private static void NoRedirect(string uri)
{
var request = (HttpWebRequest)WebRequest.Create(uri);
request.AllowAutoRedirect = false;
var resp = (HttpWebResponse)request.GetResponse();
Console.WriteLine(resp.StatusCode);
Console.WriteLine("Location: {0}", resp.Headers["Location"]);
using (var reader = new StreamReader(resp.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
}
In C# i need to POST some data to a web server using HTTP. I keep getting errors returned by the web server and after sniffing throught the data I dound that the problem is that thew Content-type header is still set to "text/html" and isn't getting changed to "application/json; Charset=UTF-8" as in my program. I've tried everything I can think of that might stop it getting changed, but am out of ideas.
Here is the function that is causing problems:
private string post(string uri, Dictionary<string, dynamic> parameters)
{
//Put parameters into long JSON string
string data = "{";
foreach (KeyValuePair<string, dynamic> item in parameters)
{
if (item.Value.GetType() == typeof(string))
{
data += "\r\n" + item.Key + ": " + "\"" + item.Value + "\"" + ",";
}
else if (item.Value.GetType() == typeof(int))
{
data += "\r\n" + item.Key + ": " + item.Value + ",";
}
}
data = data.TrimEnd(',');
data += "\r\n}";
//Setup web request
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(Url + uri);
wr.KeepAlive = true;
wr.ContentType = "application/json; charset=UTF-8";
wr.Method = "POST";
wr.ContentLength = data.Length;
//Ignore false certificates for testing/sniffing
wr.ServerCertificateValidationCallback = delegate { return true; };
try
{
using (Stream dataStream = wr.GetRequestStream())
{
//Send request to server
dataStream.Write(Encoding.UTF8.GetBytes(data), 0, data.Length);
}
//Get response from server
WebResponse response = wr.GetResponse();
response.Close();
}
catch (WebException e)
{
MessageBox.Show(e.Message);
}
return "";
}
The reason i'm getting problems is because the content-type stays as "text/html" regardless of what I set it as.
Thanks in advence.
As odd as this might sound, but this worked for me:
((WebRequest)httpWebRequest).ContentType = "application/json";
this changes the internal ContentType which updates the inherited one.
I am not sure why this works but I would guess it has something to do with the ContentType being an abstract property in WebRequest and there is some bug or issue in the overridden one in HttpWebRequest
A potential problem is that you're setting the content length based on the length of the string, but that's not necessarily the correct length to send. That is, you have in essence:
string data = "whatever goes here."
request.ContentLength = data.Length;
using (var s = request.GetRequestStream())
{
byte[] byteData = Encoding.UTF8.GetBytes(data);
s.Write(byteData, 0, data.Length);
}
This is going to cause a problem if encoding your string to UTF-8 results in more than data.Length bytes. That can happen if you have non-ASCII characters (i.e. accented characters, symbols from non-English languages, etc.). So what happens is your entire string isn't sent.
You need to write:
string data = "whatever goes here."
byte[] byteData = Encoding.UTF8.GetBytes(data);
request.ContentLength = byteData.Length; // this is the number of bytes you want to send
using (var s = request.GetRequestStream())
{
s.Write(byteData, 0, byteData.Length);
}
That said, I don't understand why your ContentType property isn't being set correctly. I can't say that I've ever seen that happen.
I am getting problems making a http POST. The API I am calling is asking for the content-length. But I am unsure how to do this.
Here is the code I have:
public static string publishClip(string instance_url, string sessionId, string clipId)
{
int trev = System.Text.ASCIIEncoding.Unicode.GetByteCount(instance_url + "/services/apexrest/DesktopClient/PublishClip/" + clipId);
WebRequest wrGETURL;
wrGETURL = WebRequest
.Create(instance_url
+ "/services/apexrest/DesktopClient/PublishClip/"
+ clipId);
wrGETURL.Method = "POST";
wrGETURL.ContentType = "application/json";
wrGETURL.ContentLength = trev;
wrGETURL.Headers.Add("Authorization", "Bearer " + sessionId);
Stream objStreamclipId = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStreamclipId);
return "trev";
}
Can anyone help me out please?
This is the error I am getting:
{"You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse."}
var postData = ?;
byte[] bytes = encoding.GetBytes(postData);
wrGETURL.ContentLength = bytes.Length;
Is your postData Trev?
You will need to get the Bytes from your StreamReader objReader. To do so, see here: How to convert an Stream into a byte[] in C#? and count them.
So i'm making a program where you input some information. One part of the information requires alot of text, we are talking 100+ characters. What I found is when the data is to large it won't send the data at all. Here is the code I am using:
public void HttpPost(string URI, string Parameters)
{
// this is what we are sending
string post_data = Parameters;
// this is where we will send it
string uri = URI;
// create a request
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
// this is important - make sure you specify type this way
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
}
I am then calling that method like so:
HttpPost(url, "data=" + accum + "&pass=HRS");
'accum' is the large amount of data that I am sending. This method works if I send a small amount of data. But then when it's large it won't send. Is there any way to send a post request to a .php page on my website that can exceed 100+ characters?
Thanks.
You're only calling GetRequestStream. That won't make the request - by default it will be buffered in memory, IIRC.
You need to call WebRequest.GetResponse() to actually make the request to the web server.
So change the end of your code to:
// Using statement to auto-close, even if there's an exception
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postBytes, 0, postBytes.Length);
}
// Now we're ready to send the data, and ask for a response
using (WebResponse response = request.GetResponse())
{
// Do you really not want to do anything with the response?
}
I'm using this way to post JSON data inside the request , I guess it's a little bit different but it may work ,
httpWebRequest = (HttpWebRequest)WebRequest.Create(RequestURL);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
String username = "UserName";
String password = "passw0rd";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{" +
"\"user\":[ \"" + user + "\"] " +
"}";
sw.Write(json);
sw.Flush();
sw.Close();
}
using (HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
//var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
}
httpResponse.Close();
}