【问题标题】:How to write a HTTP Request如何编写 HTTP 请求
【发布时间】:2011-10-26 21:11:05
【问题描述】:

您好,我尝试用 C#(Post)编写 HTTP 请求,但我需要帮助解决错误

解释:我想将 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());
    }
}

这里我收到了 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>

错误信息:

{
    "form_errors": {
      "__all__": [
        "Sorry, an error occurred while processing the container."
       ]
    }
}

如果有人可以帮助我解决问题,将非常有帮助!

【问题讨论】:

标签: c# post httprequest


【解决方案1】:

您没有设置内容长度,这可能会导致问题。您也可以尝试将字节直接写入流,而不是先将其转换为 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());
        }
    }

过去,我个人发现这样的帖子有点“烦躁”。您也可以尝试在请求中设置 ProtocolVersion。

【讨论】:

    【解决方案2】:

    我会简化你的代码,像这样:

    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));
        }
    }
    

    它还确保请求参数被正确编码。

    【讨论】:

    【解决方案3】:
    public string void decryptContainer(string dlc_content) //why not return a string, let caller decide what to do with it.
    {
        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";//sure this is needed? Maybe just match the one content-type you expect.
        using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
        {
            writer.Write("content=" + Uri.EscapeDataString(dlc_content));//escape the value of dlc_content so that the entity sent is valid application/x-www-form-urlencoded
        }
        using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())//this should be disposed when finished with.
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            return reader.ReadToEnd();
        }
    }
    

    实际发送的内容可能仍然存在问题。

    【讨论】:

      【解决方案4】:

      我马上看到的一个问题是您需要对 content 参数的值进行 URL 编码。为此使用HttpUtility.UrlEncode()。 除此之外可能还有其他问题,但很难说不知道服务是做什么的。这个错误太笼统了,可能意味着什么

      【讨论】:

        【解决方案5】:

        request.ContentLength 也应该设置。

        另外,您使用 ASCII 编码与 UTF8 编码有什么原因吗?

        【讨论】:

        • HttpWebRequest 默认设置 ContentLength 本身。 application/x-www-form-urlencoded 将始终在 ASCII 范围内,因此两种编码之间是相同的。
        【解决方案6】:

        首先获取与响应关联的流,然后将其传递给 Streamreader,如下所示:

            Stream receiveStream = response.GetResponseStream();       
        
            using (StreamReader reader = new StreamReader(receiveStream, Encoding.ASCII))
            {
                Console.WriteLine(reader.ReadToEnd());
            }
        

        【讨论】:

          【解决方案7】:

          因为我无法评论 Jon Hanna 的解决方案。这为我解决了它: Uri.EscapeDataString

                  // this is what we are sending
                  string post_data = "content=" + Uri.EscapeDataString(dlc_content);
          
                  // this is where we will send it
                  string uri = "http://dcrypt.it/decrypt/paste";
          
                  // create a request
                  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                  request.KeepAlive = false;
                  request.ProtocolVersion = HttpVersion.Version10;
                  request.Method = "POST";
          
                  // turn our request string into a byte stream
                  byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
          
                  // this is important - make sure you specify type this way
                  request.ContentType = "application/x-www-form-urlencoded";
                  request.ContentLength = postBytes.Length;
          
                  Stream requestStream = request.GetRequestStream();
          
                  // now send it
                  requestStream.Write(postBytes, 0, postBytes.Length);
                  requestStream.Close();
          
                  // grab te response and print it out to the console along with the status code
                  HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                  Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
                  Console.WriteLine(response.StatusCode);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-07-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多