Asked  7 Months ago    Answers:  5   Viewed   78 times

Here's the code I'm using:

// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";


// turn our request string into a byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(json);

// this is important - make sure you specify type this way
request.ContentType = "application/json; charset=UTF-8";
request.Accept = "application/json";
request.ContentLength = postBytes.Length;
request.CookieContainer = Cookies;
request.UserAgent = currentUserAgent;
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();
string result;
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
{
    result = rdr.ReadToEnd();
}

return result;

When I'm running this, I'm always getting 500 internal server error.

What am I doing wrong?

 Answers

70

The way I do it and is working is:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = "{"user":"test"," +
                  ""password":"bla"}";

    streamWriter.Write(json);
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

I wrote a library to perform this task in a simpler way, it is here: https://github.com/ademargomes/JsonRequest

Hope it helps.

Tuesday, June 1, 2021
 
Zach
answered 7 Months ago
57

As far as I understand, your goal is to log in and keep the session active inside the WebBrowser. If so, you have a few options:

  • First, navigate the WebBrowser to www.asite.net, to establish the session.

  • Then obtain the underlying WebBrowser ActiveX control and use IWebBrowser2::Navigate2 method, it has PostData parameter which allows to do an HTTP POST request.

  • Or, inject and execute some JavaScript which would use XHR to post the form the AJAX way.

  • Or, use WebBrowser.Document as dynamic to create a hidden form element, populate it and submit it, in the same way you'd do with JavaScript.

  • Or, use COM XMLHTTPobject to send a POST request, it shares the session with the WebBrowser.

  • You could also use some low level UrlMon API to send a POST request.

Updated, here is an example of creating and submitting a :

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.Loaded += MainWindow_Loaded;
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        NavigatedEventHandler handler = null;
        handler = delegate
        {
            this.webBrowser.Navigated -= handler;

            dynamic document = this.webBrowser.Document;
            var form = document.createElement("form");
            form.action = "http://requestb.in/tox7drto";
            form.method = "post";

            var input = document.createElement("input");
            input.type = "text";
            input.name = "name_1";
            input.value = "value_1";
            form.appendChild(input);

            input = document.createElement("input");
            input.type = "submit";
            form.appendChild(input);

            document.body.appendChild(form);
            input.click();
        };

        this.webBrowser.Navigated += handler;
        this.webBrowser.Navigate("about:blank");
    }
}
Saturday, May 29, 2021
 
cyber_truite
answered 7 Months ago
72

Filesystems do not support "inserting" data in the middle of a file. If you really have a need for a file that can be written to in a sorted kind of way, I suggest you look into using an embedded database.

You might want to take a look at SQLite or BerkeleyDB.

Then again, you might be working with a text file or a legacy binary file. In that case your only option is to rewrite the file, at least from the insertion point up to the end.

I would look at the FileStream class to do random I/O in C#.

Monday, June 14, 2021
 
Trott
answered 6 Months ago
15

Ok I've got it guys.

I had two problems.

  1. HTTP 1.1/ 100 continue

    I solved this by setting

    System.Net.ServicePointManager.Expect100Continue = false;
    
  2. The server repsonded with 422 because of a problem related to the cookies. The POST request needs to transmit a cookie container, that contains a cookie with the current session id. If this session id is not transmitted, the Server will respond with 422. In order to be able to have a cookie with the session id, I had to perform a simple HTTP-request on the login page. This request returned a cookie container with the needed session id. Then I passed the returned cookie container to POST request.

    //cookie container of previous request
    postRequest.CookieContainer = cookieContainer; 
    

With this settings the POST request could be sent successfully.

Thanks for your help.

Thursday, August 26, 2021
 
Craig Ringer
answered 4 Months ago
80

I think 2 problems have been identified here.

  1. You're using PostUrlEncodedAsync, which is going to send the data in URL-encoded format, like this: name=device:domain\login&pwd=123456. If you want the data serialized to JSON, use PostJsonAsync instead.

  2. You're only including the nested attributes object of the JSON and not the entire object.

In short, you're going to want something like this:

var result = await "https://IP/api/aaaLogin.json".PostJsonAsync(new
{
    aaaUser = new
    {
        attributes = new
        {
            name = "device:domain\login",
            pwd = "123456"
        }
    }
});

Once you get this far, you're going to need to know how to process the results. If the response is JSON formatted, you'll likely want to append .ReceiveJson() or .ReceiveJson<T>() to the above call in order to have a more friendly object to work with. Please refer to the documentation.

Sunday, October 17, 2021
 
Momhain
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share