I have to send a file since a cURL command :
curl -X POST -F "csv[file]=#/mypath.csv" https://mylogin:mypassword#the-server.net
Si i tried with an HttpClient :
var client = new HttpClient();
// Create the HttpContent for the form to be posted.
var requestContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("csv[file]", $#"#/{this.pathFile}")});
// Get the response.
HttpResponseMessage response = await client.PostAsync($#"https://{this.login}:{this.password}#myserver.net",requestContent);
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
var testResult= await reader.ReadToEndAsync();
}
Or with the following code :
WebRequest request = WebRequest.Create($#"https://{this.login}:{this.password}#myserver.net");
// Set the Network credentials
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = $#"csv[file]=#/{this.pathFile}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response2 = request.GetResponse())
{
// Display the status.
Console.WriteLine(((HttpWebResponse)response2).StatusDescription);
// Get the stream containing content returned by the server.
using (StreamReader reader = new StreamReader(response2.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
}
But each time, it's the result 401 Unauthorized. Of course, my credentials are the good ones...
[EDIT]
I work for a professional project. the server where to send the file belongs to a partner. The cURL command is imposed on me and i haven't got control of this server
[EDIT 2]
I did an analysis with wireshark
IP 229 is the partners server
IP 160 is my compuer
I just have an encrypted alert. I tested with HTTP and not https but i have the same message
It Looks like that the file you are accessing is placed at a point where the user did not have any right to access the file, Try to give permission to the folder of read and write access to use the file.
That could solve your issue.
Related
We have a program that has been running for years making API calls to a web server using HttpWebRequest and yesterday it started giving an error (something like "connection forcibly closed by remote host"). The request works just fine when made through a web browser so I would love to be able to see the difference in requests. With the Firefox developer console, I can see the raw request that is made through the browser (that works) and I need to compare that to the http request that is made from our program. It seems like it should be simple (and very useful) to stream the request out to a string or a file so I can look at it (but I have not had any luck finding how to do that).
Can you tell me how to modify the below code to store the request that HttpWebRequest would send to a file or a string (instead of a network stream)?
public string Post(string uri, string data, string contentType, string method = "POST")
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
request.Method = method;
using(Stream requestBody = request.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
You can't simply log the httprequest. Because you should also consider logging all the headers.
I suggest you to use some http sniffer to log the traffic(if you can't debug or modify your code)
In addition you can catch the exceptions by using WebException and get the raw error message from the server. Maybe it'll give you idea what the problem is.
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var responseString = reader.ReadToEnd();
}
}
I'm trying to get a simple response from a local .net site of my own. (Really I'm just trying to see what the content-body looks like from the server side.) Here is the controller method that's sending the response:
public HttpResponseMessage Post([FromBody]string value)
{
data.Add(value);
var msg = Request.CreateResponse(HttpStatusCode.Created);
msg.Headers.Location = new Uri(Request.RequestUri + "/" + (data.Count-1).ToString());
msg.Content = new StringContent(value);
return msg;
}
And here is the code that's making the request:
HttpWebRequest request;
request = (HttpWebRequest)WebRequest.Create ("http://localhost:50203/api/Values");
request.Method = "POST";
try
{
WebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
byte[] requestBody = ASCIIEncoding.ASCII.GetBytes(HttpUtility.UrlEncode("grant_type=client_credentials"));
request.ContentLength = requestBody.Length;
dataStream.Write(requestBody, 0, requestBody.Length);
StreamReader reader = new StreamReader(dataStream);
myString = reader.ReadToEnd();
}
I'm getting the response message: HTTP Error 411. The request must be chunked or have a content length. But as you can see I DO assign the content length in the line: request.ContentLength = requestBody.Length;.
Why am I getting this error?
Thanks to help from itsme86 I was able to see what was happening. It had to do with misunderstanding the HttpWebRequest method. I was trying to set the content length and write to the request after I'd already posted it using the GetResponse method. I should have posted the length first. This wasn't a particularly good question, and no one else should answer.
i have few application attached to new relic. when i enter my api key and hit SEND REQUEST i get my response in json format.
curl -X GET 'https://api.newrelic.com/v2/applications.json' \
-H 'X-Api-Key:<api key>' -i
this is what the request goes. i dont know what the above code is. well i need to read the returned json message in C# and may be then deserialize the json message.
i tried this
public ActionResult Index()
{
WebRequest wr = WebRequest.Create("https://api.newrelic.com/v2/applications.json");
wr.ContentType = "application/json";
wr.Method = "GET";
//wr.Headers["X-Parse-REST-API-Key"] = "<my api key>";
wr.Headers.Add("Authorization", "<my api key>");
using (WebResponse response = wr.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
int x = 10;
}
}
but i get 500 error.
Your code is very close to working. You just need to change your request header a bit as shown below (and substitute your own api key). Then, as you say you will need to deserialize the json. I've tested this bit of code and it returned the equivalent of the curl command.
WebRequest wr = WebRequest.Create("https://api.newrelic.com/v2/applications.json");
wr.ContentType = "application/json";
wr.Method = "GET";
wr.Headers.Add("X-Api-Key:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
using (WebResponse response = wr.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
byte[] bytes = new Byte[10000];
int n = stream.Read(bytes, 0, 9999);
string s = System.Text.Encoding.ASCII.GetString(bytes);
}
}
As you probably know, you can use our api explorer to form the http request needed to extract the data you are interested in. Then you should be able to copy the request from api explorer to your c# code. See the api explorer docs here: https://docs.newrelic.com/docs/features/getting-started-with-new-relics-api-explorer.
public void HttpsRequest(string address)
{
string data;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
byte[] resp = new byte[(int)response.ContentLength];
Stream receiveStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(receiveStream, Encoding.ASCII))
{
data = reader.ReadToEnd();
}
}
I get an Arithmetic operation resulted in an overflow when I am trying to read a page over https. Errors occur because the response gives me ContentLenght = -1.
Using fiddler I can see that the page was received. Some other websites using HTTPS works fine but most of them not.
If I query https://www.google.com, I get the same error message, because not every response has a content length. Use this code to avoid the problem:
public static void HttpsRequest(string address)
{
string data;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
data = reader.ReadToEnd();
}
}
}
This behavior is expected: not every response contains content length.
There is nothing in your sample that requires length to be known, so simply not reading it maybe enough.
From HttpWebResponse.ContentLength Property
The ContentLength property contains the value of the Content-Length header returned with the response. If the Content-Length header is not set in the response, ContentLength is set to the value -1.
If Content-Length header is not set it does not mean that you got a bad response.
This may be a pathetically simple problem, but I cannot seem to format the post webrequest/response to get data from the Wikipedia API. I have posted my code below if anyone can help me see my problem.
string pgTitle = txtPageTitle.Text;
Uri address = new Uri("http://en.wikipedia.org/w/api.php");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string action = "query";
string query = pgTitle;
StringBuilder data = new StringBuilder();
data.Append("action=" + HttpUtility.UrlEncode(action));
data.Append("&query=" + HttpUtility.UrlEncode(query));
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream.
StreamReader reader = new StreamReader(response.GetResponseStream());
divWikiData.InnerText = reader.ReadToEnd();
}
You might want to try a GET request first because it's a little simpler (you will only need to POST for wikipedia login). For example, try to simulate this request:
http://en.wikipedia.org/w/api.php?action=query&prop=images&titles=Main%20Page
Here's the code:
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://en.wikipedia.org/w/api.php?action=query&prop=images&titles=Main%20Page");
using (HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse())
{
string ResponseText;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
ResponseText = reader.ReadToEnd();
}
}
Edit: The other problem he was experiencing on the POST request was, The exception is : The remote server returned an error: (417) Expectation failed. It can be solved by setting:
System.Net.ServicePointManager.Expect100Continue = false;
(This is from: HTTP POST Returns Error: 417 "Expectation Failed.")
I'm currently in the final stages of implementing an C# MediaWiki API which allows the easy scripting of most MediaWiki viewing and editing actions.
The main API is here: http://o2platform.googlecode.com/svn/trunk/O2%20-%20All%20Active%20Projects/O2_XRules_Database/_Rules/APIs/OwaspAPI.cs and here is an example of the API in use:
var wiki = new O2MediaWikiAPI("http://www.o2platform.com/api.php");
wiki.login(userName, password);
var page = "Test"; // "Main_Page";
wiki.editPage(page,"Test content2");
var rawWikiText = wiki.raw(page);
var htmlText = wiki.html(page);
return rawWikiText.line().line() + htmlText;
You seem to be pushing the input data on HTTP POST, but it seems you should use HTTP GET.
From the MediaWiki API docs:
The API takes its input through
parameters in the query string. Every
module (and every action=query
submodule) has its own set of
parameters, which is listed in the
documentation and in action=help, and
can be retrieved through
action=paraminfo.
http://www.mediawiki.org/wiki/API:Data_formats