简体   繁体   中英

HttpWebRequest to NSUrlConnection/NSUrlSession or HttpClient (with ModerHttpClient lib)

We have code written in Xamarin Cross Platform that works for Android with Clients tunneling software:

           string body = "<rest_access/>";

           byte[] dataByte = Encoding.ASCII.GetBytes(body);

           HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint + @"/rest_access");
           request.Method = "POST";
           request.ContentType = "application/xml";
           request.Accept = "application/json";

           var credentials = System.Text.Encoding.ASCII.GetBytes(username + ":" + password);
           string encodedCredentials = System.Convert.ToBase64String(credentials);
           request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + encodedCredentials);

           request.ContentLength = dataByte.Length;

           Stream stream = request.GetRequestStream();

           stream.Write(dataByte, 0, dataByte.Length);

           try
           {
               HttpWebResponse response = (HttpWebResponse)request.GetResponse();
               StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
               string responseString = reader.ReadToEnd().ToString();

               dynamic authResponse = JsonConvert.DeserializeObject(responseString);
               //Console.WriteLine("Auth response:\n" + authResponse);

               accessKey = authResponse.rest_access.access_key;

               //Console.WriteLine("kljuc " + accessKey);

               return accessKey;
           }
           catch (Exception ex)
           {
               Console.WriteLine(ex.Message);
               return "Unexpected Error";
           }


But when using this same code for iOS application tunnel does not seem to be present.
In their documentation we found:

Apps built with the Xamarin development platform can access network servers in various ways. AppTunnel with HTTP/S tunneling is supported only as follows:
• The app uses the NSURLConnection or NSURLSession APIs exposed to C# through the Xamarin.iOS binding.
• The app uses the ModernHttpClient library with NSURLSession. The ModernHttpClient library with CFNetwork will not work.
For example, the app initializes the instance of the ModernHttpClient as follows:
var httpClient = new HttpClient (new NativeMessageHandler ());

Does this mean that we have to rewrite all methods that used HttpWebRequest in them to now use one of these libs?
If so could I get some link to How to rewrite these so they are acceptable?

Have you tried to set the HttpClient Implementation for Xamarin.iOS in HttpClient Stack

change it to NSUrlSession or Managed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM