polling with HttpWebRequest

829 Views Asked by At

I'm using this API that accepts an image and sends back the description of it's contents. According to the docs, the cURL looks like this:

 curl -i -X POST \
-H "Authorization: CloudSight [key]" \
-F "image_request[image][email protected]" \
-F "image_request[locale]=en-US" \
https://api.cloudsightapi.com/image_requests

My code for sending the request is as below:

var request = (HttpWebRequest)WebRequest.Create(cloudsight_url);
request.Method = "POST";
request.Headers.Add("Authorization", "CloudSight R6USrcKxMym0EP2peuYtVA");
string s1 = string.Format("image_request[locale]={0}&image_request[remote_image_url]={1}", "en-US", imgurl);

// Send Data
StreamWriter myWriter = null;
myWriter = new StreamWriter(request.GetRequestStream());
myWriter.Write(s1);
myWriter.Close();
var response1 = (HttpWebResponse)request.GetResponse();
string result2 = "";

using (StreamReader streamReader = new StreamReader(response1.GetResponseStream()))
{
    var output = streamReader.ReadToEnd();
    streamReader.Close();
    result2 = output.ToString();    
}

The request is sent successfully, however the service returns { "status" : "not completed" }. In the docs, it says to continue polling for a response until the { "status" : "completed" } response is returned. How do I acheive this?

1

There are 1 best solutions below

9
MeterLongCat On

As you pointed out the documentation states that you should continue polling until the response has been marked completed.

All you really need to do is to put your HTTP web request into a loop that continues until completion. Probably also a good idea to exit the loop after a certain time without success to avoid looping infinitely. Putting the loop onto a separate thread might also be wise.