Hello I try to write a HTTP Request in C# (Post), but I need help with an error
Expl: I want to send the Content of a DLC File to the Server and recive the decrypted content.
C# Code
public static void decryptContainer(string dlc_content)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
writer.Write("content=" + dlc_content);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
}
and here I got the html request
<form action="/decrypt/paste" method="post">
<fieldset>
<p class="formrow">
<label for="content">DLC content</label>
<input id="content" name="content" type="text" value="" />
</p>
<p class="buttonrow"><button type="submit">Submit ยป</button></p>
</fieldset>
</form>
Error Message:
{
"form_errors": {
"__all__": [
"Sorry, an error occurred while processing the container."
]
}
}
Would be very helpfull if someone could help me solving the problem!
You haven't set a content-length, which might cause issues. You could also try writing bytes directly to the stream instead of converting it to ASCII first.. (do it the opposite way to how you're doing it at the moment), eg:
public static void decryptContainer(string dlc_content)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
byte[] _byteVersion = Encoding.ASCII.GetBytes(string.Concat("content=", dlc_content));
request.ContentLength = _byteVersion.Length
Stream stream = request.GetRequestStream();
stream.Write(_byteVersion, 0, _byteVersion.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
}
I've personally found posting like this to be a bit "fidgity" in the past. You could also try setting the ProtocolVersion on the request.
I would simplify your code, like this:
public static void decryptContainer(string dlc_content)
{
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "content", dlc_content }
};
client.Headers[HttpRequestHeader.Accept] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
string url = "http://dcrypt.it/decrypt/paste";
byte[] result = client.UploadValues(url, values);
Console.WriteLine(Encoding.UTF8.GetString(result));
}
}
It also ensures that the request parameters are properly encoded.
public string void decryptContainer(string dlc_content) //why not return a string, let caller decide what to do with it.
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";//sure this is needed? Maybe just match the one content-type you expect.
using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
writer.Write("content=" + Uri.EscapeDataString(dlc_content));//escape the value of dlc_content so that the entity sent is valid application/x-www-form-urlencoded
}
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())//this should be disposed when finished with.
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
There could still be a problem with what is actually being sent.
One issue I see right away is that you need to URL encode value of the content parameter. Use HttpUtility.UrlEncode() for that.
Other than that there might be other issues there, but it is hard to say not knowing what service does. The error is too generic and could mean anything
request.ContentLength should be set as well.
Also, is there a reason you are ASCII encoding vs UTF8?
Get the stream associated with the response first then pass that into the Streamreader as below:
Stream receiveStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(receiveStream, Encoding.ASCII))
{
Console.WriteLine(reader.ReadToEnd());
}
As I can't comment on the solution of Jon Hanna. This solved it for me:
Uri.EscapeDataString
// this is what we are sending
string post_data = "content=" + Uri.EscapeDataString(dlc_content);
// this is where we will send it
string uri = "http://dcrypt.it/decrypt/paste";
// 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();
// grab te response and print it out to the console along with the status code
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
Console.WriteLine(response.StatusCode);
Related
I am sending post request with pdf file attached example.pdf - this file is added to project in Visual Studio as "content". Problem is that I am receiving 400 Bad request.
API server is receiving (IFormFile uploadedFile) but in my case uploadedFile is null.
Authorization is good, url, headers also. I checked it via postman and it is working properly.
requestbody in debug mode is '{byte[63933]}'
How to solve this in C#?
string pathToPdfFile = "Scenarios\DefaultScenario\example.pdf";
byte[] requestBody = File.ReadAllBytes(pathToPdfFile);
public static string PostRequestUploadFile(string url, Dictionary<string, string> headersDictionary, byte[] requestbody)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
if (headersDictionary != null)
{
foreach (KeyValuePair<string, string> entry in headersDictionary)
{
request.Headers.Add(entry.Key, entry.Value);
}
}
request.ContentType = "application/pdf";
Stream dataStream = request.GetRequestStream();
byte[] byteArray = requestbody;
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
catch (Exception Ex)
{
return Ex.ToString();
}
}
I have made some changes
I added the Content Length header
You may have to change application/pdf to application/x-www-form-urlencoded
Finally, I don't know which parameters you are sending in headersDictionary, but may be missing the form 'file' field name
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST"; // Consider using WebRequestMethods.Http.Post instead of "POST"
if (headersDictionary != null){
foreach (KeyValuePair<string, string> entry in headersDictionary){
request.Headers.Add(entry.Key, entry.Value);
}
}
request.ContentType = "application/pdf";
// Dependending on your server, you may have to change
// to request.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = requestbody; // I don't know why you create a new variable here
request.ContentLength = byteArray.Length;
using (var dataStream = request.GetRequestStream()){
dataStream.Write(byteArray, 0, byteArray.Length);
}
using(var response = (HttpWebResponse)request.GetResponse()){
using(var reader = new StreamReader(response.GetResponseStream())){
return reader.ReadToEnd();
}
}
In my tests using this I have to use request.ContentType = "application/x-www-form-urlencoded" instead of PDF (I can't mock your entire setup)
As I don't have the server you are trying to send this and don't have the parameters I can't test this in your environment
For future reference, HttpWebRequest is a Legacy (obsolete) implementation that should be avoided and new implementations should use HttpClient read more
I'am trying to use example api call in below link please check link
http://sendloop.com/help/article/api-001/getting-started
My account is "code5" so i tried 2 codes to get systemDate.
1. Code
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
2.Code
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
But i don't know that i use correctly api by above codes ?
When i use above codes i don't see any data or anything.
How can i get and post api to Sendloop.And how can i use api by using WebRequest ?
I will use api first time in .net so
any help will be appreciated.
Thanks.
It looks like you need to post your API key to the endpoint when making requests. Otherwise, you will not be authenticated and it will return an empty response.
To send a POST request, you will need to do something like this:
var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json");
request.ContentType = "application/json; charset=utf-8";
string postData = "APIKey=xxxx-xxxxx-xxxxx-xxxxx-xxxxx";
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(data, 0, data.Length); // Send the data.
newStream.Close();
string text;
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
string userAuthenticationURI =
"https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ originZip +
"&destinations="+ DestinationZip + "&units=imperial&language=en-
EN&sensor=false&key=Your API Key";
if (!string.IsNullOrEmpty(userAuthenticationURI))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(userAuthenticationURI);
request.Method = "GET";
request.ContentType = "application/json";
WebResponse response = request.GetResponse();
var responseString = new
StreamReader(response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(responseString);
}
I would like to write a class in c# which should send an HTTP request (post) to a PHP file which is on my server in order to retrieve a json object.
This is the code I've got:
public void SendRequest(){
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("url");
// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
}
Is that what I need? What do you think I should change or improve?
Thank you for your help.
You need to post data and read the response:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
string yourPostData = "Your post data";
string sreverResponseText;
byte[] postDataBytes = Encoding.UTF8.GetBytes(yourPostData);
request.ContentLength = yourPostData.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
using (response = (HttpWebResponse)request.GetResponse())
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
sreverResponseText = streamReader.ReadToEnd();
Now what you are looking for is in sreverResponseText, also you can access headers from response.Headers.ToString()
I am trying to replicate a Couch database using .NET classes instead of a curl command line. I have never used WebRequest or Httpwebrequest before, but I am attempting to use them to make a post request with the script below.
Here is the JSON script for couchdb replication(I know this works):
{ ""_id"":"database_replicate8/7/12", "source":sourcedb, ""target"":"targetDB", ""create_target"":true, ""user_ctx"": { ""roles"": ["myrole"] } }
The above script is put into a text file, sourcefile.txt. I want to take this line and put it in a POST web request using .NET functionality.
After looking into it, I chose to use the httpwebrequest class. Below is what I have so far--I got this from http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
HttpWebRequest bob = (HttpWebRequest)WebRequest.Create("sourceDBURL");
bob.Method = "POST";
bob.ContentType = "application/json";
byte[] bytearray = File.ReadAllBytes(#"sourcefile.txt");
Stream datastream = bob.GetRequestStream();
datastream.Write(bytearray, 0, bytearray.Length);
datastream.Close();
Am I going about this correctly? I am relatively new to web technologies and still learning how http calls work.
Here is a method I use for creating POST requests:
private static HttpWebRequest createNewPostRequest(string apikey, string secretkey, string endpoint)
{
HttpWebRequest request = WebRequest.Create(endpoint) as HttpWebRequest;
request.Proxy = null;
request.Method = "POST";
//Specify the xml/Json content types that are acceptable.
request.ContentType = "application/xml";
request.Accept = "application/xml";
//Attach authorization information
request.Headers.Add("Authorization", apikey);
request.Headers.Add("Secretkey", secretkey);
return request;
}
Within my main method I call it like this:
HttpWebRequest request = createNewPostRequest(apikey, secretkey, endpoint);
and I then pass my data to the method like this:
string requestBody = SerializeToString(requestObj);
byte[] byteStr = Encoding.UTF8.GetBytes(requestBody);
request.ContentLength = byteStr.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteStr, 0, byteStr.Length);
}
//Parse the response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
//Business error
if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine(string.Format("Error: response status code is{0}, at time:{1}", response.StatusCode, DateTime.Now.ToString()));
return "error";
}
else if (response.StatusCode == HttpStatusCode.OK)//Success
{
using (Stream respStream = response.GetResponseStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(SubmitReportResponse));
reportReq = serializer.Deserialize(respStream) as SubmitReportResponse;
}
}
...
In my case I serialize/deserialize my body from a class - you will need to alter this to use your text file. If you want an easy drop in solution, then change the SerializetoString method to a method that loads your text file to a string.
I am looking for an example of how, in C#, to put a xml document in the message body of a http request and then parse the response. I've read the documentation but I would just like to see an example if there's one available. Does anyone have a example?
thanks
private static string WebRequestPostData(string url, string postData)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.ContentType = "text/xml";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return null;
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
return sr.ReadToEnd().Trim();
}
}
}
You should use the WebRequest class.
There is an annotated sample available here to send data:
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx