简体   繁体   中英

HTTPwebresponse not working, I can't get anything to POST

So I get a bad request error whenever I run this. I have looked on stack overflow but can't seem to get any of the responses from users to work. Any help would be appreciated.

//Make a request to the SendGrid API to add the email address to the globabl unsubscirbe

        HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("https://api.sendgrid.com/v3/asm/suppressions/global");
        request1.Headers.Add("authorization", "My_API_KEY");
        string Data = "{" + "recipient_emails:[" + "\"" +(txtEmail.Text) + "\"" + "]}"; //place body here
        request1.Method = "POST";
        request1.ContentType = "application/json";

        using (StreamWriter sw = new StreamWriter(request1.GetRequestStream()))
        {

            sw.Write(Data);

        }

        HttpWebResponse response1= (HttpWebResponse)request1.GetResponse();

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

It is an excerpt.

var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");

var client = new SendGridClient(apiKey);

string data = @"{
  'recipient_emails': [
    'test1@example.com', 
    'test2@example.com'
  ]
}";
Object json = JsonConvert.DeserializeObject<Object>(data);
data = json.ToString();
var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "asm/suppressions/global", requestBody: data);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Body.ReadAsStringAsync().Result);
Console.WriteLine(response.Headers.ToString());
Console.ReadLine();

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