【发布时间】:2015-05-21 11:46:53
【问题描述】:
我想记录(保存到数据库或文件等)所有请求和响应,但 WebClient 除外。 我使用派生类: public class GzipWebClient : WebClient {...}
我应该在哪里捕获带有数据的上传请求、下载响应和异常?还是应该重写一些方法?
我可以使用“protected override WebRequest GetWebRequest(Uri address)”来捕获数据吗?
一些使用:
private T GetDeserializedResponse<T>(string url)
{
using (var wc = new GzipWebClient())
{
wc.Encoding = Encoding.UTF8;
string fullUrl = BaseUrl + url;
string response = wc.DownloadString(fullUrl);
try
{
return JsonConvert.DeserializeObject<T>(response);
}
catch
{
_logger.Error(response);
throw;
}
}
}
或
string url = shop.Warehouse != null ?
string.Format("/api/v1/cabinet/{0}/shop_create.json", MasterApiKey) :
string.Format("/api/v1/{0}/shop_create.json", MasterApiKey);
string name = shop.Name;
string namePostfix = DateTime.Now.ToString("yyMMddhhmmss");
if ((name + namePostfix).Length > 64)
name = name.Substring(0, 64 - namePostfix.Length);
string data = shop.Warehouse != null ?
string.Format("name={0}&warehouse={1}&address={2}", name + namePostfix, shop.Warehouse.Id, shop.Address) :
string.Format("name={0}&address={1}", name + namePostfix, shop.Address);
using (var wc = new GzipWebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
string fullUrl = BaseUrl + url;
string response = wc.UploadString(fullUrl, data);
var shopData = JsonConvert.DeserializeObject<DDeliveryCreateShopResponse>(response);
if (!shopData.Success)
{
throw new DeliveryCreateStoreException(shop.Name);
}
if (string.IsNullOrEmpty(shopData.IdKeyPair.Key))
{
throw new DeliveryCreateStoreException(shop.Name);
}
shop.Id = shopData.IdKeyPair.Id;
shop.Key = shopData.IdKeyPair.Key;
return shop;
}
【问题讨论】:
-
请放一些代码,调用,除了方法之外的其他东西; GzipWebClient 做什么?我们可以查看您如何/何时加载网页吗?