2016-01-27
zelder
2018-09-14
27/01
2016

Простой Web-запрос на .NET


Пример POST запроса


public void Request()
{
            Uri uri = new Uri("https://api.zedk.ru/api/login/");
            WebRequest request = HttpWebRequest.Create(uri);
            request.Credentials = CredentialCache.DefaultCredentials;
            ((HttpWebRequest)request).UserAgent = "zedk worker";
            ((HttpWebRequest)request).Accept = "text/html,application/xhtml+xml,application/xml;";
            request.Proxy = null;
            request.Method = "POST";
            request.ContentType = "text/html; charset=utf-8";
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            //! params
            NameValueCollection outgoingQueryString = new NameValueCollection();
            outgoingQueryString.Add("login", "yourlogin");
            outgoingQueryString.Add("password", "yourpass");
            string postData = outgoingQueryString.ToString();
            //+ to bytes
            ASCIIEncoding ascii = new ASCIIEncoding();
            byte[] postBytes = ascii.GetBytes(postData.ToString());
            request.ContentLength = postBytes.Length;
            //! add post data to request
            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(postBytes, 0, postBytes.Length);
                postStream.Flush();
            }
            try
            {
                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader responseReader = new StreamReader(response.GetResponseStream()))
                    {
                        string responseData = responseReader.ReadToEnd(); // ОТВЕТ
                    }
                }
            }
            catch(Exception e)
            {
                _onError(e);
            }
}

private bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}

Пример GET запроса


Запрос GET будет чуть иначе. Параметры передаются иначе.


//+ request
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(watchItem.GetAddress());
httpWebRequest.UserAgent = $"mybrowser"; //"Mozilla/5.1 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
//x httpWebRequest.AllowAutoRedirect = false;
// авторизация
httpWebRequest.UseDefaultCredentials = true;
httpWebRequest.PreAuthenticate = true;
httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
//! просим
try
{
//WebResponse webResponse = await httpWebRequest.GetResponseAsync(); //.GetResponse();
using (HttpWebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
 if (webResponse == null) return result;
 result.HasError = false;
 result.StatusCode = webResponse.StatusCode;
 using (Stream stream = webResponse.GetResponseStream())
 {
  // TODO: читаем ответ
 }
}
}
catch (WebException e)
{
result.HasError = true;
if (e.Response != null && e.Response is HttpWebResponse) // в частности, сюда попадает 404 0_о
{
 var resp = (HttpWebResponse)e.Response;
 result.ErrorStr = $"{resp.StatusCode.ToString()} ({(int)resp.StatusCode})";
 result.StatusCode = resp.StatusCode;
}
else
{
 //result.ErrorStr = e.Status.ToString();
 result.ErrorStr = e.Message;
}
}
catch (Exception e)
{
result.HasError = true;
result.ErrorStr = e.Message;
// log
if (_onError != null) _onError(e);
}




.