How to write a HTTP Request

2020-02-04 15:33发布

Hello I try to write a HTTP Request in C# (Post), but I need help with an error

Expl: I want to send the Content of a DLC File to the Server and recive the decrypted content.

C# Code

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

and here I got the html request

<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>

Error Message:

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

Would be very helpfull if someone could help me solving the problem!

7条回答
够拽才男人
2楼-- · 2020-02-04 15:48

I would simplify your code, like this:

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

It also ensures that the request parameters are properly encoded.

查看更多
\"骚年 ilove
3楼-- · 2020-02-04 15:49

One issue I see right away is that you need to URL encode value of the content parameter. Use HttpUtility.UrlEncode() for that. Other than that there might be other issues there, but it is hard to say not knowing what service does. The error is too generic and could mean anything

查看更多
看我几分像从前
4楼-- · 2020-02-04 15:52

You haven't set a content-length, which might cause issues. You could also try writing bytes directly to the stream instead of converting it to ASCII first.. (do it the opposite way to how you're doing it at the moment), eg:

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

I've personally found posting like this to be a bit "fidgity" in the past. You could also try setting the ProtocolVersion on the request.

查看更多
等我变得足够好
5楼-- · 2020-02-04 15:52

As I can't comment on the solution of Jon Hanna. This solved it for me: 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);
查看更多
Fickle 薄情
6楼-- · 2020-02-04 15:53

request.ContentLength should be set as well.

Also, is there a reason you are ASCII encoding vs UTF8?

查看更多
贪生不怕死
7楼-- · 2020-02-04 15:57

Get the stream associated with the response first then pass that into the Streamreader as below:

    Stream receiveStream = response.GetResponseStream();       

    using (StreamReader reader = new StreamReader(receiveStream, Encoding.ASCII))
    {
        Console.WriteLine(reader.ReadToEnd());
    }
查看更多
登录 后发表回答