我有一个简单的cli程序,它获取一个mac地址和机器名,创建一个包含此信息的post字符串,并尝试使用.net的WebBrowser.Naviate方法通过POST发送它。除了发送的POST数据外,一切似乎都在工作。每当我打印出PHP的Post数组的内容时,我得到一个空数组。我错过了某个地方的一步吗?
C#控制台应用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Net.NetworkInformation;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Windows.Forms;
using System.Threading;
namespace machine_boot
{
class Program
{
static void Main(string[] args)
{
try
{
// Get the system mac address
string theMac = GetMacAddress();
System.Threading.ThreadStart objThreadStart = delegate
{
string postData = "mm=" + theMac + "&mn=" + System.Environment.MachineName;
WebBrowser browserObject = new WebBrowser();
browserObject.Navigate(
"https://siteurl.com/test.php",
"_blank",
System.Text.Encoding.UTF8.GetBytes(postData),
"Content-Type: application/x-www-form-urlencoded" + Environment.NewLine
);
};
Thread theThread = new Thread(objThreadStart);
theThread.SetApartmentState(ApartmentState.STA);
theThread.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Contact an administrator");
Console.WriteLine();
Console.WriteLine("Press any key exit...");
Console.ReadLine();
}
}
/// <summary>
/// Finds the MAC address of the NIC with maximum speed.
/// </summary>
/// <returns>The MAC address.</returns>
static string GetMacAddress()
{
const int MIN_MAC_ADDR_LENGTH = 12;
string macAddress = string.Empty;
long maxSpeed = -1;
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
string tempMac = nic.GetPhysicalAddress().ToString();
if (nic.Speed > maxSpeed &&
!string.IsNullOrEmpty(tempMac) &&
tempMac.Length >= MIN_MAC_ADDR_LENGTH)
{
maxSpeed = nic.Speed;
macAddress = tempMac;
}
}
return macAddress;
}
}
/*
* The class we map the json server response to
*/
[DataContract]
public class ServerResponse
{
[DataMember]
public string machineurl { get; set; }
}
}
siteurl.com/test.php
echo "<pre>";
echo var_export($_POST, true);
更新
我找到了apache的access.log文件并进行了一些实验。我找到了最初的POST请求:
"POST /test.php HTTP/1.1" 200 0 325 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"
然后我从postData变量中删除了第二个get参数,以查看请求大小是否已更改,如下所示:
"POST /test.php HTTP/1.1" 200 0 296 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"
所以我知道正在发出POST请求,并且POST数据包含在请求中。 apache解析字节数组会有问题吗?值得注意的是,每次发出POST请求时,都会立即发出额外的GET请求,之后我认为这很奇怪:
"POST /test.php HTTP/1.1" 200 0 325 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"
"GET /test.php HTTP/1.1" 200 0 269 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"
答案 0 :(得分:0)
我认为你应该在?
的开头丢失postData
。
问号用于在GET请求中将路径与查询参数分开。
对于POST请求,特别是您正在使用的application/x-www-form-urlencoded,您只需传递URL编码的参数,形成key=value
对,由&
分隔。无需?
。
另外,请尝试将最后一个参数更改为"Content-Type: application/x-www-form-urlencoded" + Environment.NewLine
。