I am getting an error when trying to create an ad unit. When I execute the API, I am getting the error "The remote server returned an error: (400) Bad Request.".
Below is the code I am using. Do you see anything wrong with this? (The approach I am using is working fine for some other API calls like List adClients.
public static void CreateAdUnit(string accountId)
{
string access_token = System.Web.HttpContext.Current.Session["Google_Access_Token"] as string;
StringBuilder postBuilder = new StringBuilder();
postBuilder.AppendFormat("{0}={1}", "key", Uri.EscapeUriString(apiKey));
postBuilder.AppendFormat("&{0}={1}", "access_token", Uri.EscapeUriString(access_token));
string hostUrl = "
https://www.googleapis.com/adsensehost/v4.1/accounts/" + accountId + "/adclients/ca-" + accountId + "/adunits";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(hostUrl + "?" + postBuilder.ToString());
request.Method = "POST";
request.Accept = "text/json";
AdSenseAdUnitResource adUnitResource = new AdSenseAdUnitResource();
adUnitResource.contentAdsSettings = new AdSenseAdContentAdsSettings();
adUnitResource.contentAdsSettings.backupOption = new AdSenseAdBackupOption();
adUnitResource.contentAdsSettings.backupOption.color = "FFFFFF";
adUnitResource.contentAdsSettings.size = "SIZE_300_250";
adUnitResource.contentAdsSettings.type = "TEXT";
adUnitResource.customStyle = new AdSenseAdCustomStyle();
adUnitResource.customStyle.corners = "VERY_ROUNDED";
adUnitResource.customStyle.font = new AdSenseAdCustomStyleFont();
adUnitResource.customStyle.font.family = "ACCOUNT_DEFAULT_FAMILY";
adUnitResource.customStyle.font.size = "ACCOUNT_DEFAULT_SIZE";
adUnitResource.customStyle.colors = new AdSenseAdCustomStyleColors();
adUnitResource.customStyle.colors.background = "FFFFFF";
adUnitResource.customStyle.colors.border = "FF0000";
adUnitResource.customStyle.colors.text = "00FF00";
adUnitResource.customStyle.colors.title = "000000";
adUnitResource.customStyle.colors.url = "0000FF";
adUnitResource.name = "Demo Ad1";
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonData = js.Serialize(adUnitResource);
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(jsonData);
streamWriter.Flush();
streamWriter.Close();
}
try // Get the response of the POST
{
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string responseData = sr.ReadToEnd().Trim();
}
catch (WebException wex)
{
// The remote server returned an error: (400) Bad Request.
throw wex;
}
catch
{
throw;
}
}
Thanks.