Goo*_*les 13 c# post httprequest
您好我尝试在C#(Post)中编写HTTP请求,但我需要有关错误的帮助
Expl:我想将DLC文件的内容发送到服务器并重新发送解密的内容.
C#代码
public static void decryptContainer(string dlc_content)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
writer.Write("content=" + dlc_content);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
}
Run Code Online (Sandbox Code Playgroud)
在这里我收到了html请求
<form action="/decrypt/paste" method="post">
<fieldset>
<p class="formrow">
<label for="content">DLC content</label>
<input id="content" name="content" type="text" value="" />
</p>
<p class="buttonrow"><button type="submit">Submit »</button></p>
</fieldset>
</form>
Run Code Online (Sandbox Code Playgroud)
错误信息:
{
"form_errors": {
"__all__": [
"Sorry, an error occurred while processing the container."
]
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人可以帮助我解决问题,那将非常有帮助!
che*_*ova 13
您尚未设置内容长度,这可能会导致问题.您也可以尝试将字节直接写入流而不是首先将其转换为ASCII.(这与您此刻的操作方式相反),例如:
public static void decryptContainer(string dlc_content)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
byte[] _byteVersion = Encoding.ASCII.GetBytes(string.Concat("content=", dlc_content));
request.ContentLength = _byteVersion.Length
Stream stream = request.GetRequestStream();
stream.Write(_byteVersion, 0, _byteVersion.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
}
Run Code Online (Sandbox Code Playgroud)
我个人发现这样的帖子在过去有点"狡猾".您还可以尝试在请求上设置ProtocolVersion.
我会简化你的代码,像这样:
public static void decryptContainer(string dlc_content)
{
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "content", dlc_content }
};
client.Headers[HttpRequestHeader.Accept] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
string url = "http://dcrypt.it/decrypt/paste";
byte[] result = client.UploadValues(url, values);
Console.WriteLine(Encoding.UTF8.GetString(result));
}
}
Run Code Online (Sandbox Code Playgroud)
它还确保正确编码请求参数.