Arvind Chourasiya

Arvind Chourasiya

  • NA
  • 933
  • 130.6k

How to covert HttpWebRequest implementation to HttpClient

Nov 6 2018 2:17 AM
have one service method which is using HttpWebRequest for below stuff
 
  1. while (ub < sentCount)  
  2. {  
  3.     ub = step * (1 + (i++));  
  4.   
  5.     var k = (ub > sentCount) ? (sentCount) : ub; //to avoid array out of range exception(assign unitll array length if calc exceeds)  
  6.   
  7.     for (int j = lb; j < k; j++)  
  8.     {  
  9.         pnos = pnos + "," + pnosList[j].Phone;  
  10.     }  
  11.     pnos = pnos.Substring(1);  
  12.   
  13.     var sbPostData = new StringBuilder();  
  14.     sbPostData.AppendFormat("authkey={0}", api.AuthenticationKey);  
  15.     sbPostData.AppendFormat("&mobiles={0}", pnos);  
  16.     sbPostData.AppendFormat("&message={0}", message);  
  17.     sbPostData.AppendFormat("&sender={0}", api.SenderId);  
  18.     sbPostData.AppendFormat("&route={0}""default");  
  19.     string sendSMSUri = api.EndPoint;  
  20.   
  21.   
  22.     // Create HTTPWebrequest  
  23.     var httpWReq = (HttpWebRequest)WebRequest.Create(sendSMSUri);  
  24.     //Prepare and Add URL Encoded data  
  25.     var encoding = new UTF8Encoding();  
  26.     byte[] data = encoding.GetBytes(sbPostData.ToString());  
  27.     //Specify post method  
  28.     httpWReq.Method = "POST";  
  29.     httpWReq.ContentType = "application/x-www-form-urlencoded";  
  30.     //httpWReq.ContentLength = data.Length;  
  31.     using (Stream stream = httpWReq.GetRequestStream())  
  32.     {  
  33.         stream.Write(data, 0, data.Length);  
  34.     }  
  35.     //Get the response  
  36.     var response = (HttpWebResponse)httpWReq.GetResponse();  
  37.     var reader = new StreamReader(response.GetResponseStream());  
  38.     string responseString = reader.ReadToEnd();  
  39.   
  40.     //Close the response  
  41.     reader.Close();  
  42.     response.Close();  
  43.   
  44.     lb = ub;  
  45.     pnos = string.Empty;  
  46. }  
Now the same thing I need to do in HttpClient is it possible to do that. Issue I am facing is HttpWebRequest is not supporting in PCL(C# class library) I want to move above logic to PCL.
 

Answers (1)