[英]Curl Request In C#
I am trying to curl file contents to an external source. 我正在尝试将文件内容卷曲到外部源。 I can curl it correctly from the command line, but I am having problem sending the string in the -d switch in code.
我可以从命令行正确地卷曲它,但是在代码中的-d开关中发送字符串时遇到问题。 Here is the gist of the curl command
这是curl命令的要点
curl.exe -u userName:password -H "Content-Type: text/plain" -X PUT https://someIp/command?filename=filename.txt -d "content of filename.text is here" --insecure
I can send the file, and they receive it on the other end, the problem is that the content of the file isn't making it over to them. 我可以发送文件,而对方又可以接收文件,问题是文件的内容没有传递给他们。 Does anyone have any experience or ideas here?
有人在这里有任何经验或想法吗? Here is the code from my proof of concept.
这是我的概念证明中的代码。
ServicePointManager.ServerCertificateValidationCallback = new
System.Net.Security.RemoteCertificateValidationCallback
(
delegate { return true; }
);
// create the requst address to send the file to
string requestAddress = string.Format("{0}{1}", this.CurlAddress, Path.GetFileName(fileName));
// spin up the request object, set neccessary paramaters
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(requestAddress);
request.ContentType = "text/plain";
request.Method = "PUT";
request.Credentials = new NetworkCredential("userName", "password");
// open the web request stream
using (var stream = request.GetRequestStream())
{
// create a writer to the request stream
using (var writer = new StringWriter())
{
// write the text to the stream
writer.Write(File.ReadAllLines(fileName));
stream.Close();
}
}
// Get the response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
Console.WriteLine(string.Format("Response: {0}", responseString));
}
The problem was that I wasn't writing the file contents to the stream from the requests .GetRequestStream(). 问题是我没有从.GetRequestStream()请求中将文件内容写入流中。 Once I wrote the contents there, it appeared on the other end.
一旦我将内容写入那里,它就会出现在另一端。 New stripped down code is
新的精简代码是
// open the web request stream
using (var stream = request.GetRequestStream())
{
byte[] file = File.ReadAllBytes(fileName);
stream.Write(file, 0, file.Length);
stream.Close();
}
I think what you're after is Put
with string content. 我认为您追求的是
Put
字符串内容。 This can easily be done asynchronously with an HttpClient
. 使用
HttpClient
可以轻松地异步完成此操作。
private static HttpClient client = new HttpClient();
private async Task CurlFileContents(Uri uri, string contents)
{
var content = new StringContent(contents, Encoding.Default, "text/plain");
var repsonse = await client.PutAsync(uri, content);
var responseContent = await repsonse.Content.ReadAsStringAsync();
//operate on response
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.