Подтвердить что ты не робот

Как написать HTTP-запрос

Здравствуйте, я пытаюсь написать HTTP-запрос в С# (Post), но мне нужна помощь с ошибкой

Объяснение: Я хочу отправить содержимое файла DLC на сервер и получить дешифрованный контент.

Код С#

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."
       ]
    }
}

Было бы очень полезно, если бы кто-нибудь помог мне решить проблему!

4b9b3361

Ответ 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

Одна из проблем, которые я сразу вижу, - это то, что вам нужно кодировать значение URL параметра content. Для этого используйте HttpUtility.UrlEncode(). Помимо этого могут быть и другие проблемы, но трудно сказать, не зная, что делает служба. Ошибка слишком общая и может означать что-либо

Ответ 5

request.ContentLength также должен быть установлен.

Кроме того, есть ли причина, по которой вы кодируете ASCII и UTF8?

Ответ 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);