C# 来自Google Analytics API的错误请求错误
//请帮助使此代码可行C# 来自Google Analytics API的错误请求错误,c#,google-analytics-api,ssis-2012,C#,Google Analytics Api,Ssis 2012,//请帮助使此代码可行 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Xml.Linq; using System.Globalization; namespace GoogleAnalyticsSupport
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml.Linq;
using System.Globalization;
namespace GoogleAnalyticsSupport
{
public class ReportRequestorWithSorting
{
#region Fields
//I am getting bad request error
private static readonly string requestUrlFormat = "https://www.googleapis.com/analytics/v3/data?ids={1}&metrics={2}&sort={3}&start-date={4}&end-date={5}&start-index={6}&max-results={7}";
private static readonly string authUrlFormat = "accountType=GOOGLE&Email={0}&Passwd={1}&source=reimers.dk-analyticsreader-0.1&service=analytics";
private static CultureInfo ci = CultureInfo.GetCultureInfo("en-US");
private string _token = null;
private string _username = null;
private string _password = null;
#endregion
#region Constructor
public ReportRequestorWithSorting() { }
public ReportRequestorWithSorting(string email, string password)
{
_username = email;
_password = password;
}
#endregion
#region Properties
public string Email
{
get { return _username; }
set
{
if (!string.Equals(_username, value))
{
_username = value;
_token = null;
}
}
}
public string Password
{
get { return _password; }
set
{
if (!string.Equals(_password, value))
{
_password = value;
_token = null;
}
}
}
#endregion
#region Methods
\\struggling to replace the new authentication method\\
private string GetToken(string username, string password)
{
if (string.IsNullOrEmpty(_username) || string.IsNullOrEmpty(_password))
{
throw new ArgumentNullException("Username, Password", "Username and/or password not set");
}
string authBody = string.Format(authUrlFormat, username, password);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://accounts.google.com/o/oauth2/auth");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.UserAgent = "Example.dk req";
Stream stream = req.GetRequestStream();
StreamWriter sw = new StreamWriter(stream);
sw.Write(authBody);
sw.Close();
sw.Dispose();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string token = sr.ReadToEnd();
string[] tokens = token.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in tokens)
{
if (item.StartsWith("Auth="))
{
return item.Replace("Auth=", "");
}
}
return string.Empty;
}
public IEnumerable<AnalyticsAccountInfo> GetAccounts()
{
if (string.IsNullOrEmpty(_token))
{
_token = GetToken(_username, _password);
}
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.googleapis.com/analytics/v2.4/management/accounts");
req.Headers.Add("Authorization: GoogleLogin auth=" + _token);
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream);
string responseXml = sr.ReadToEnd();
XDocument doc = XDocument.Parse(responseXml);
XNamespace dxpSpace = doc.Root.GetNamespaceOfPrefix("dxp");
XNamespace defaultSpace = doc.Root.GetDefaultNamespace();
var entries = from en in doc.Root.Descendants(defaultSpace + "entry")
select new AnalyticsAccountInfo
{
AccountID = en.Elements(dxpSpace + "property").Where(xe => xe.Attribute("name").Value == "ga:accountId").First().Attribute("value").Value,
AccountName = en.Elements(dxpSpace + "property").Where(xe => xe.Attribute("name").Value == "ga:accountName").First().Attribute("value").Value,
ID = en.Element(defaultSpace + "id").Value,
Title = en.Element(defaultSpace + "title").Value,
ProfileID = en.Elements(dxpSpace + "property").Where(xe => xe.Attribute("name").Value == "ga:profileId").First().Attribute("value").Value,
WebPropertyID = en.Elements(dxpSpace + "property").Where(xe => xe.Attribute("name").Value == "ga:webPropertyId").First().Attribute("value").Value
};
return entries;
}
private XDocument getReport(AnalyticsAccountInfo account, IEnumerable<Dimension> dimensions, IEnumerable<Metric> metrics
, IEnumerable<Sort> sorts, DateTime from, DateTime to, int startindex = 1, int maxresults = 250)
{
if (string.IsNullOrEmpty(_token))
{
_token = GetToken(_username, _password);
}
StringBuilder dims = new StringBuilder();
foreach (Dimension item in dimensions)
{
dims.Append("ga:" + item.ToString() + ",");
}
StringBuilder mets = new StringBuilder();
foreach (Metric item in metrics)
{
mets.Append("ga:" + item.ToString() + ",");
}
StringBuilder srt = new StringBuilder();
foreach (Sort item in sorts)
{
srt.Append("-" + "ga:" + item.ToString() + ",");
}
string requestUrl = string.Format(requestUrlFormat, "ga:" + account.ProfileID, dims.ToString().Trim(",".ToCharArray()), mets.ToString().Trim(",".ToCharArray())
, srt.ToString().Trim(",".ToCharArray()), from.ToString("yyyy-MM-dd"), to.ToString("yyyy-MM-dd"), startindex, maxresults);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
req.Headers.Add("Authorization: GoogleLogin auth=" + _token);
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream responseStream = response.GetResponseStream();
string responseXml = new StreamReader(responseStream, Encoding.UTF8, true).ReadToEnd();
XDocument doc = XDocument.Parse(responseXml);
return doc;
}
public IEnumerable<GenericEntry> ReportRequestWF(AnalyticsAccountInfo account, IEnumerable<Dimension> dimensions, IEnumerable<Metric> metrics
, IEnumerable<Sort> sorts, DateTime from, DateTime to, int startindex = 1, int maxresults = 250)
{
XDocument doc = getReport(account, dimensions, metrics
, sorts, from, to, startindex, maxresults);
XNamespace dxpSpace = doc.Root.GetNamespaceOfPrefix("dxp");
XNamespace defaultSpace = doc.Root.GetDefaultNamespace();
var gr = from r in doc.Root.Descendants(defaultSpace + "entry")
select new GenericEntry
{
Dimensions = new List<KeyValuePair<Dimension, string>>(
from rd in r.Elements(dxpSpace + "dimension")
select new KeyValuePair<Dimension, string>(
(Dimension)Enum.Parse(
typeof(Dimension),
rd.Attribute("name").Value.Replace("ga:", ""),
true),
rd.Attribute("value").Value)),
Metrics = new List<KeyValuePair<Metric, string>>(
from rm in r.Elements(dxpSpace + "metric")
select new KeyValuePair<Metric, string>(
(Metric)Enum.Parse(typeof(Metric), rm.Attribute("name").Value.Replace("ga:", ""), true),
rm.Attribute("value").Value)),
Sorts = new List<KeyValuePair<Sort, string>>(
from rs in r.Elements(dxpSpace + "sort")
select new KeyValuePair<Sort, string>(
(Sort)Enum.Parse(typeof(Sort), rs.Attribute("name").Value.Replace("ga:", ""), true),
rs.Attribute("value").Value))
};
return gr;
}
#endregion
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
Net系统;
使用System.IO;
使用System.Xml.Linq;
利用制度全球化;
命名空间分析支持
{
公共类ReportRequestorWithSorting
{
#区域字段
//我收到错误的请求错误
私有静态只读字符串requestUrlFormat=”https://www.googleapis.com/analytics/v3/data?ids={1} &metrics={2}&sort={3}&start date={4}&end date={5}&start index={6}&max results={7}”;
私有静态只读字符串authUrlFormat=“accountType=GOOGLE&Email={0}&Passwd={1}&source=reimers.dk-analyticsreader-0.1&service=analytics”;
私有静态CultureInfo ci=CultureInfo.GetCultureInfo(“en-US”);
私有字符串_token=null;
私有字符串_username=null;
私有字符串_password=null;
#端区
#区域构造函数
public ReportRequestorWithSorting(){}
公共报告请求者排序(字符串电子邮件、字符串密码)
{
_用户名=电子邮件;
_密码=密码;
}
#端区
#区域属性
公共字符串电子邮件
{
获取{return\u username;}
设置
{
如果(!string.Equals(_username,value))
{
_用户名=值;
_令牌=null;
}
}
}
公共字符串密码
{
获取{return\u password;}
设置
{
如果(!string.Equals(_password,value))
{
_密码=值;
_令牌=null;
}
}
}
#端区
#区域方法
\\正在努力替换新的身份验证方法\\
私有字符串GetToken(字符串用户名、字符串密码)
{
if(string.IsNullOrEmpty(_用户名)| | string.IsNullOrEmpty(_密码))
{
抛出新的ArgumentNullException(“用户名、密码”、“未设置用户名和/或密码”);
}
string authBody=string.Format(authUrlFormat、用户名、密码);
HttpWebRequest请求=(HttpWebRequest)HttpWebRequest.Create(“https://accounts.google.com/o/oauth2/auth");
请求方法=“POST”;
req.ContentType=“应用程序/x-www-form-urlencoded”;
req.UserAgent=“Example.dk req”;
Stream=req.GetRequestStream();
StreamWriter sw=新StreamWriter(流);
sw.Write(authBody);
sw.Close();
sw.Dispose();
HttpWebResponse响应=(HttpWebResponse)req.GetResponse();
StreamReader sr=新的StreamReader(response.GetResponseStream());
字符串标记=sr.ReadToEnd();
string[]tokens=token.Split(新字符串[]{“\n”},StringSplitOptions.RemoveEmptyEntries);
foreach(令牌中的字符串项)
{
if(item.StartsWith(“Auth=))
{
返回项。替换(“Auth=”,“”);
}
}
返回字符串。空;
}
公共IEnumerable GetAccounts()
{
if(string.IsNullOrEmpty(_标记))
{
_令牌=GetToken(\u用户名,\u密码);
}
HttpWebRequest请求=(HttpWebRequest)HttpWebRequest.Create(“https://www.googleapis.com/analytics/v2.4/management/accounts");
添加(“授权:GoogleLogin auth=“+”令牌);
HttpWebResponse响应=(HttpWebResponse)req.GetResponse();
Stream responseStream=response.GetResponseStream();
StreamReader sr=新的StreamReader(responseStream);
字符串responseXml=sr.ReadToEnd();
XDocument doc=XDocument.Parse(responseXml);
XNamespace dxpSpace=doc.Root.GetNamespaceOfPrefix(“dxp”);
XNamespace defaultSpace=doc.Root.GetDefaultNamespace();
var entries=来自doc.Root.subjects中的en(defaultSpace+“entry”)
选择新的AnalyticsAccountInfo
{
AccountID=en.Elements(dxpSpace+“property”)。其中(xe=>xe.Attribute(“name”).Value==“ga:AccountID”).First().Attribute(“Value”).Value,
AccountName=en.Elements(dxpSpace+“property”)。其中(xe=>xe.Attribute(“name”).Value==“ga:AccountName”).First().Attribute(“Value”).Value,
ID=en.Element(defaultSpace+“ID”).值,
Title=en.元素(defaultSpace+“Title”).值,
ProfileID=en.Elements(dxpSpace+“property”)。其中(xe=>xe.Attribute(“name”).Value==“ga:ProfileID”).First().Attribute(“Value”).Value,
WebPropertyID=en.Elements(dxpSpace+“property”)。其中(xe=>xe.Attribute(“name”).Value==“ga:WebPropertyID”).First().Attribute(“Value”).Value
};
返回条目;
}
私有XDocument getReport(AnalyticsAccountInfo帐户、IEnumerable维度、IEnumerable度量
,IEnumerable排序,DateTime from,DateTime to,int startindex=1,int maxresults=250)
{
if(string.IsNullOrEmpty(_标记))
{
_令牌=GetToken(\u用户名,\u密码);
}
StringBuilder dims=新的StringBuilder();
foreach(维度中的维度项)
{
追加(“ga:+item.ToString()+”,”;
}
StringBuilder mets=新的StringBuilder();
foreach(度量中的度量项目)
{
mets.Append(“ga:+item.ToString()+”,”;
}
StringBuilder srt=新的StringBuilder();
foreach(排序中的排序项)
{
srt.Append(“-”+“ga:“+item.ToString()+”,”);
}
string requestUrl=string.Format(requestUrlFormat,“ga:”+account.ProfileID,dims.ToString().Trim(“,”.tocharray()),mets.ToString().Trim(“,”.tocharray())
,srt.ToString().Trim(“,”.ToCharArray()),from.ToString(“yyyy-MM-dd”),to.ToString(“yyy-MM-dd”),startindex,maxresults);
HttpWebRequest req=(HttpWebRequest)HttpWebRequest.Create(requestUrl);
添加(“授权:GoogleLogin auth=“+”令牌);
HttpWebResponse响应=(HttpWebResponse)req.GetResponse();
Stream responseStream=response.GetResponseStream();
字符串responseXml=newstreamreader(responseStream,Encoding.UTF8,true);
XDocument doc=XDocument.Parse(responseXml);
退货单;
}
public IEnumerable ReportRequestWF(AnalyticsAccountInfo帐户、IEnumerable维度、IEnumerable度量
,IEnumerable sorts,DateTime from,DateT