C# WebClient 未将数据正确发布到 PHP 脚本
C# WebClient not posting data correctly to PHP script
C#:
using (WebClient client = new WebClient()) {
byte[] response = client.UploadValues("http://example.com/api/server/key",
new NameValueCollection() {
{ "key", key }
});
string result = Encoding.UTF8.GetString(response);
Console.WriteLine(result);
}
PHP:
$key = $_POST["key"];
echo($key);
当它运行时,PHP $_POST 数组从未有任何实际发布到它的值。表示回显线没有输出。
此外,是的,'key' 确实有一个值,它只是在这个例子中被裁剪掉了。
url 将值编码为:
client.UploadValues("http://example.com/api/server/key", new NameValueCollection()
{
{ "key", HttpUtility.UrlEncode(key) }
});
我不确定,表达式 new NameValueCollection() { ... }
做了您认为应该做的事情。
你应该明确地说
NameValueCollection values = new NameValueCollection();
values.Add("key", key);
byte[] response = client.UploadValues("http://example.com/api/server/key",
values);
搜索对象初始值设定项显示 Collection initializers
Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable or a class with an Add extension method.
还有一个例子
List<Cat> cats = new List<Cat>
{
new Cat(){ Name = "Sylvester", Age=8 },
new Cat(){ Name = "Whiskers", Age=2 },
new Cat(){ Name = "Sasha", Age=14 }
};
所以也许使用不带括号的初始化器是可行的,例如
byte[] response = client.UploadValues("http://example.com/api/server/key",
new NameValueCollection {
{ "key", key }
});
C#:
using (WebClient client = new WebClient()) {
byte[] response = client.UploadValues("http://example.com/api/server/key",
new NameValueCollection() {
{ "key", key }
});
string result = Encoding.UTF8.GetString(response);
Console.WriteLine(result);
}
PHP:
$key = $_POST["key"];
echo($key);
当它运行时,PHP $_POST 数组从未有任何实际发布到它的值。表示回显线没有输出。
此外,是的,'key' 确实有一个值,它只是在这个例子中被裁剪掉了。
url 将值编码为:
client.UploadValues("http://example.com/api/server/key", new NameValueCollection()
{
{ "key", HttpUtility.UrlEncode(key) }
});
我不确定,表达式 new NameValueCollection() { ... }
做了您认为应该做的事情。
你应该明确地说
NameValueCollection values = new NameValueCollection();
values.Add("key", key);
byte[] response = client.UploadValues("http://example.com/api/server/key",
values);
搜索对象初始值设定项显示 Collection initializers
Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable or a class with an Add extension method.
还有一个例子
List<Cat> cats = new List<Cat>
{
new Cat(){ Name = "Sylvester", Age=8 },
new Cat(){ Name = "Whiskers", Age=2 },
new Cat(){ Name = "Sasha", Age=14 }
};
所以也许使用不带括号的初始化器是可行的,例如
byte[] response = client.UploadValues("http://example.com/api/server/key",
new NameValueCollection {
{ "key", key }
});