2017-03-27 55 views
0

我使用Sendgrid API發送電子郵件,但它顯示錯誤「遠程服務器返回錯誤:(400)錯誤的請求。」並在catch塊結果給出消息「{」errors「:[」Bad username/password「],」message「:」error「}」。我使用下面的代碼: -Sendgrid API給出

 string api_user = "apiuser"; 
     string api_key = "Key"; 
     string toAddress = "[email protected]"; 
     string toName = "To Name"; 
     string subject = "A message from SendGrid"; 
     string text = "Delivered by your friends at SendGrid."; 
     string fromAddress = "[email protected]"; 

     string url = "https://sendgrid.com/api/mail.send.json"; 

     // Create a form encoded string for the request body 
     string parameters = "api_user=" + api_user + "&api_key=" + api_key + "&to=" + toAddress + 
          "&toname=" + toName + "&subject=" + subject + "&text=" + text + 
          "&from=" + fromAddress; 

     try 
     { 
      //Create Request 
      HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); 
      myHttpWebRequest.Method = "POST"; 
      myHttpWebRequest.ContentType = "application/x-www-form-urlencoded"; 
      //myHttpWebRequest.ContentType = "text/xml"; 

      // Create a new write stream for the POST body 
      StreamWriter streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream()); 

      // Write the parameters to the stream 
      streamWriter.Write(parameters); 
      streamWriter.Flush(); 
      streamWriter.Close(); 

      // Get the response 
      HttpWebResponse httpResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 

      // Create a new read stream for the response body and read it 
      StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()); 
      string result = streamReader.ReadToEnd(); 

      // Write the results to the console 
      //Console.WriteLine(result); 
     } 
     catch (WebException ex) 
     { 
      // Catch any execptions and gather the response 
      HttpWebResponse response = (HttpWebResponse)ex.Response; 

      // Create a new read stream for the exception body and read it 
      StreamReader streamReader = new StreamReader(response.GetResponseStream()); 
      string result = streamReader.ReadToEnd(); 
      return result; 
      // Write the results to the console 
      //Console.WriteLine(result); 
     } 

回答

0

嘗試使用Uri.EscapeDataString的參數

var parameters = "api_user=" + Uri.EscapeDataString(api_user) 
        + "&api_key=" + Uri.EscapeDataString(api_key) + //more values 

編輯:

你也可以嘗試將您parameters轉換成字節數組:

byte[] parametersData = Encoding.UTF8.GetBytes(parameters); 
// Write the parameters to the stream 
streamWriter.Write(parametersData);