我必须从REST服务器下载数据并在SQL中填充表。所以我使用测试REST服务器站点,使用API密钥。下面的代码。
var url =“https://openexchangerates.org/api/latest.json?app_id=a28cb70b31404429bea46b0889ec6697”;
var currencyRates = CCAP_JSON_Downloader.CCAP._download_serialized_json_data<CurrencyRates>(url);
// Console.Write();
public class CCAP
{
public static T _download_serialized_json_data<T>(string url) where T : new() {
using (var w = new WebClient()) {
var json_data = string.Empty;
SqlConnection DB_CONN_1990 = new SqlConnection(ConfigurationManager.ConnectionStrings["CCAP_JSON_Downloader.Properties.Settings.DB_CONN_1990"].ToString());
DB_CONN_1990.Open();
// attempt to download JSON data as a string
//for (int i = 0; i <= 9; i++)
try
{
json_data = w.DownloadString(url);
JsonTextReader reader = new JsonTextReader(new StringReader(json_data));
while (reader.Read())
{
Console.Read();
if (reader.Value != null)
{
Console.WriteLine("CAPTURING" + "Path: {0}, Value: {1}", reader.Path, reader.Value);
var cmd = new SqlCommand("Insert_RAW_XML", DB_CONN_1990);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Token_Type", reader.Path);
cmd.Parameters.AddWithValue("@Value", reader.Value);
cmd.ExecuteNonQuery();
}
else
Console.WriteLine("Token: {0}", reader.TokenType);
现在,我可以访问状态REST服务器,但是他们使用BASIC HTTP身份验证。代码
var webRequest = (HttpWebRequest)WebRequest.Create("https://wccarest.wicourts.gov:443/api/v1/counties?expand=all&api_key");
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:28.0) Gecko/20100101 Firefox/28.0";
string autorization = "username" + ":" + "Password";
byte[] binaryAuthorization = System.Text.Encoding.UTF8.GetBytes(autorization);
autorization = Convert.ToBase64String(binaryAuthorization);
autorization = "Basic " + autorization;
webRequest.Headers.Add("AUTHORIZATION", autorization);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK) Console.WriteLine("{0}", webResponse.Headers);
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
string s = reader.ReadToEnd();
Console.WriteLine(s);
}
我的问题是,我确实喜欢以前的工作方式。我可以在哪里提供网址,var url =“https://openexchangerates.org/api/latest.json?app_id=a28cb70b31404429bea46b0889ec6697”;
但是现在,我无法弄清楚如何通过身份验证获取完整的URL。我有来自用户和密码的加密。但似乎我只能传递基本URL,所以我总是得到一个未经授权的错误。如何使用我可以传递到CCAP类的完整凭据提交URL。 第一次使用REST服务器等,所以我愿意接受任何其他建议或更好的方法来做到这一点。 谢谢 鲁迪
答案 0 :(得分:0)
尝试使用特殊网址格式:http://username:password@example.com/ - 这应该在标准HTTP&#34;授权&#34;中发送凭据。报头中。
例如,https://username:password@wccarest.wicourts.gov:443/api/v1/counties?expand=all&api_key