Aidon Hudson
Aidon Hudson

Reputation: 124

HTTP POST stuck in an infinite loop until times out?

I have sent a POST request using this code:

var postDatax = new Dictionary<string, string>
                {
                    { "korefor", "new" },
                    { "korename", "Initial" },
                    { "set_instant", "true" },
                    { "set_engine", "google" },
                    { "set_language", "en" },
                    { "set_location", "uk" },
                    { "set_mobile", "false" },
                    { "set_email", "[email protected]" },
                    { "set_mainurl", "mediaworks.co.uk" },
                    { "set_compurls", "google.com, yahoo.com" },
                    { "koreforname", "Mediaworks" },
                    { "koreforkeywords", "newcastle seo, mediaworks, orm" }
                };
using (System.Net.WebClient wc = new System.Net.WebClient())
    {
        wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        byte[] byteArrayx = System.Text.Encoding.ASCII.GetBytes(amend(postDatax));
        byte[] byteResultx = wc.UploadData("http://localhost:51378", "POST", byteArrayx);
        string responsex = Encoding.ASCII.GetString(byteResultx);
    }

When live and debugging it gets stuck and loops until times out and crashes. I'm not sure why this is the case.

The amend function:

private static string amend(Dictionary<string, string> postData)
{
    string amended = "";
    foreach (var item in postData)
    {
        amended += "&" + item.Key + "=" + item.Value;
    }
    return amended;
}

The line which the infinite loop triggers on:

byte[] byteResultx = wc.UploadData("http://localhost:51378", "POST", byteArrayx);

Any help would be appreciated.

Upvotes: 0

Views: 641

Answers (1)

Orel Eraki
Orel Eraki

Reputation: 12196

UploadData is not on an infinite loop, it's Blocking which is different.

UploadData is blocking, which is waiting until the other side, which is the server side http://localhost:51378 in this scenario, will respond to it.

A long time blocking can occur because of the following issues and other reasons as well:

  1. When a server is busy with other requests.
  2. Server code taking long time to process your request.
  3. Local or Remote firewall issues.

WebClient.UploadData Remarks from MSDN

The UploadData method sends the content of data to the server without encoding it. This method blocks while uploading the data. To continue executing while waiting for the server's response, use one of the UploadDataAsync methods.

I'm strongly recomend you to wrap the UploadData with appropriate try..catch clause

Upvotes: 1

Related Questions