简体   繁体   中英

How to add query string and json data to httpWebRequest type POST

Javacode here:

function sendTextMessage(sender, text) {
  messageData = {
    text:text
  }
  request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: {access_token:token},
    method: 'POST',
    json: {
      recipient: {id:sender},
      message: messageData,
    }
  }, function(error, response, body) {
    if (error) {
      console.log('Error sending message: ', error);
    } else if (response.body.error) {
      console.log('Error: ', response.body.error);
    }
  });
}

And C# code, I want to replace "?access_token=dshfhsfhrthytrghfgbfhnytfht" by code, because the url use type POST . I find out that I can use WebRequest but i don't know how I use WebRequest to add Json data, so I use HttpWebrequest, Http Webrequest can add query string by StringBuilder , but how i Write post data and json? In this code I just Write json data

public void sendTextMessage(string sender, string text) {
            string json = "{ recipient: {id:"+sender+ "} , message: {text: \""+text+"\"}";
            var request = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/v2.6/me/messages?access_token=dshfhsfhrthytrghfgbfhnytfht");
            request.ContentType = "application/json";
            request.Method = "POST";

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {                
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }
        }

/* Write like this You must add you variable as postdata */ var request = (HttpWebRequest)WebRequest.Create(" http://www.example.com/recepticle.aspx ");

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 responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM