通过WebApi取出XML数据

 

Get请求:

 public static Result<GetExpressCollectionResponseType> GetDataFromWebs(string waybillNumbers)
        {
            var result = new Result<GetExpressCollectionResponseType>();
            try
            {
                var url = "http://***.com.cn/service/Manage/999001/Expresses/GetExpressByEpcodes";

                var client = new WebClient();
                client.Headers.Add(HttpRequestHeader.Authorization, "basic OTk5MDAxOjEyMzQ1Njc4");
                client.Headers.Add(HttpRequestHeader.ContentType, "text/xml; charset=utf-8");

                var postbody = "<string>" + waybillNumbers + "</string>";
                var data = Encoding.UTF8.GetBytes(postbody);
                var response = client.UploadData(url, "POST", data);
              
                GetExpressCollectionResponseType t = default(GetExpressCollectionResponseType);
                var xmlSerializer = new XmlSerializer(typeof(GetExpressCollectionResponseType));
                using (Stream xmlStream = new MemoryStream(response))
                {
                    using (XmlReader xmlReader = XmlReader.Create(xmlStream))
                    {
                        Object obj = xmlSerializer.Deserialize(xmlReader);
                        t = (GetExpressCollectionResponseType)obj;
                    }
                }
                result.Entity = t;
            }
            catch (Exception ex)
            {
                result.HasError = true;
                result.ErrorMessage = ex.Message;
            }
            return result;
        }

 

 

Post请求:

 

 public static Result<string> GetLabelFromWeb(string waybillNumber, string filename, string labelSize)
        {
            var result = new Result<string>();

            try
            {
                var url = string.Format("http://***.com.cn/service/Manage/999001/Expresses/{0}/{1}Label",
                    waybillNumber, labelSize);

                var client = new WebClient();
                client.Headers.Add(HttpRequestHeader.Authorization, "basic OTk5MDAxOjEyMzQ1Njc4");
                client.Headers.Add(HttpRequestHeader.ContentType, "text/xml; charset=utf-8");

                client.DownloadFile(url, filename);

                result.Entity = filename;
            }
            catch (Exception ex)
            {
                result.HasError = true;
                result.ErrorMessage = ex.Message;
            }
            return result;
        }

 

posted @ 2015-04-16 17:07  奇风★逍遥  阅读(1132)  评论(0编辑  收藏  举报