tags:

views:

518

answers:

2

I am trying to use REST API to get friends lists from fb.

ArrayObject is filled with:

  • SecretKey
  • API_KEY Method = "facebook.friends.get"
  • call_id uid
  • v = 1.0
  • sig = md5 code

And I'm trying to make the call with:

public string GetResponse(ArrayObject Parameters)
{
    // Set the encoding type
    theRequest.ContentType = "application/x-www-form-urlencoded";

    theRequest.ContentLength = Parameters.getData().Length;

    // We write the parameters into the request
    StreamWriter sw = new StreamWriter(theRequest.GetRequestStream());
    sw.Write(Parameters.getData());
    sw.Flush();
    sw.Close();

    // Execute the query
    theResponse = (HttpWebResponse)theRequest.GetResponse();
    StreamReader sr = new StreamReader(theResponse.GetResponseStream());
    return sr.ReadToEnd();
}

But I get an exception here:

theResponse = (HttpWebResponse) theRequest.GetResponse();

with a Message of:

The remote server returned an error: (500) Internal Server Error.

A: 

I think it's because you're closing the request stream. Try moving the

sw.Close();

line after you receive the response.

EDIT: Looked at some of my old code. Corrected my own answer.

yodaj007
same problem :/
C.
+1  A: 

Your code should look like this, as you aren't disposing of some resources properly:

public string GetResponse(ArrayObject Parameters)
{
    // Set the encoding type
    theRequest.ContentType = "application/x-www-form-urlencoded";

    theRequest.ContentLength = Parameters.getData().Length;

    // We write the parameters into the request
    using (StreamWriter sw = new StreamWriter(theRequest.GetRequestStream()))
    {
        sw.Write(Parameters.getData());
        sw.Flush();
    }

    // Execute the query
    theResponse = (HttpWebResponse)theRequest.GetResponse();

    using (StreamReader sr = new StreamReader(theResponse.GetResponseStream()))
    {
        return sr.ReadToEnd();
    }
}

Also, you it appears you are caching the HttpWebResponse instance. This is a bad idea, as it derives from WebResponse, which implements IDisposable. Calling Dispose on this instance is important in order to dispose of the resources used in making the request and reading the response.

That being said, is there a reason you aren't using the Facebook Developer Toolkit? It contains classes which encapsulate most of the calls to the RESTful API, as well as mechanisms you can reuse to generate new calls (with a little code reworking) if necessary.

casperOne
this doesn't work...
C.