How to store the return value of https POSTmethod in C #

let's say i want to keep the value

 POST` method "[https://api.dropbox.com/1/oauth/request_token][1]" 

      

in a variable named

 `accessToken` of type `string`

      

(lets just asume that the post method retuns string for the sake of simplicity)

 in C # .. How to do this?

+3


source to share


2 answers


You must first declaim the string variable, for example:

string httpReturnValue = "";

      

To get the value and store it in a string, you have to do this:



var request = (HttpWebRequest)WebRequest.Create("YOUR URL");

// For example
var postData = "thing1=hello";
    postData += "&thing2=world";

var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();

var httpReturnValue= new StreamReader(response.GetResponseStream()).ReadToEnd();

      

Code from here: HTTP request with post .

+1


source


Hi Avik I am using this code to get my HttpWebResponse:

using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            //To obtain response body
                            using (Stream streamResponse = response.GetResponseStream())
                            {
                                using (StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8))
                                {
                                    var result = streamRead.ReadToEnd();

                                    if (response.Equals("1")) //It 1 in my case when operation                           is complete!!
                                    {

                                    }
                                    else
                                    {

                                    }
                                }
                            }
                        }
                    }

      



I think you can use this if you need more information or you can solve with my code, advise me! Good luck AviK!

+1


source







All Articles