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.
Related
I have a webRequest to create. So I am using (httpwebrequest)webrequest.Create("/get").
I need to send some payload/request body to this request.
But stream writer only seems to work with POST request.
How do I achieve that?
You should not attempt to use a get request to post data to a server. Instead, you should use a post request to accomplish this. It is highly recommended that you do not use a webrequest and instead use HttpClient but if for some reason you absolutely must use webrequest like if you're working with legacy code this is the basic method of accomplishing this:
try
{
WebRequest request = WebRequest.Create("http://www.server.example/api/example");
request.Method = "POST";
byte[] package = Encoding.UTF8.GetBytes("package string example");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = package.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(package, 0, package.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
using (dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
//do something with the data retrieved from the server
}
response.Close();
}
catch (Exception ex)
{
//example catch
}
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 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 got a Java Servelet like
http://152.252.271.12:9999/media/servlet/RequestProcessor.do
for this I need to pass parameters in Querystring like this
http://152.252.271.12:9999/media/servlet/RequestProcessor.do?input=abc
I need to read response back.
I tried like this.
request.Method = "POST";
request.KeepAlive = false;
request.Credentials = CredentialCache.DefaultCredentials;
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postData);
}
// Read Response.
HttpWebResponse webresponse = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(webresponse.GetResponseStream(), Encoding.Default))
{
result = reader.ReadToEnd();
logtxn.LogTxn(result, "SPDCL RESPONSE");
}
webresponse.Close();
Any help appreciated..
Use WebRequest & WebResponse classes. Check http://gsraj.tripod.com/dotnet/webgetpost.html for more information.
I've had a similar problem in the past, I had to host a service in IIS that accepted a string containing a request and returned another string with a response to that request. All of the above needed to be done using HTTP POST.
The solution I found was to host a WCF service on IIS and configure it to use HTTP GET/POST protocols.
Also I remember that I needed to use a Stream class to input and output data (a simple string would not work in this case), in other words, I had a HTTP POST method in WCF that was something like:
Stream GetData(Stream data);
Take a look at this article.
You can use the WebClient class, as a client for the servlet. For example
WebClient myWebClient = new WebClient();
// Download the Web resource and save it into a data buffer.
byte[] myDataBuffer = myWebClient.DownloadData (#"http://152.252.271.12:9999/media/servlet/RequestProcessor.do?input=abc");
// Display the downloaded data.
string download = Encoding.ASCII.GetString(myDataBuffer);
Now parse the result string download and obtain the response.
Please find the below code:
public class MyWebRequest
{
private WebRequest request;
private Stream dataStream;
private string status;
public String Status
{
get
{
return status;
}
set
{
status = value;
}
}
public MyWebRequest(string url)
{
// Create a request using a URL that can receive a post.
request = WebRequest.Create(url);
}
public MyWebRequest(string url, string method): this(url)
{
if (method.Equals("GET") || method.Equals("POST"))
{
// Set the Method property of the request to POST.
request.Method = method;
}
else
{
throw new Exception("Invalid Method Type");
}
}
public MyWebRequest(string url, string method, string data): this(url, method)
{
// Create POST data and convert it to a byte array.
string postData = data;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// 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();
}
public string GetResponse()
{
// 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();
return responseFromServer;
}
}
//create the constructor with post type and few data
MyWebRequest myRequest = new MyWebRequest("http://www.yourdomain.com", "POST", "a=value1&b=value2");
//show the response string on the console screen.
Console.WriteLine(myRequest.GetResponse());
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