OkHttp3 is able to connect but RestSharp is not to a cloudflare protected website

45 Views Asked by At

I am consuming a REST API using two methods. For Android (Xamarin) app I am using OKHttp3 and for C# WinForm application using RestSharp. API domain is behind cloudflare DNS which is using some sort of SSL handshake detection and shows Error 403 "Sorry, you have been blocked" page, when parameters are not met.

Now the problem is that its working fine with OKHttp3 but not RestSharp. Using same set of headers etc with both methods but till now no success with .NET project.

OKHttp Code:

RequestBody create = RequestBody.Create(MediaType.Parse("binary"), postdata);
Request.Builder builder = new Request.Builder();
builder.Url(url);

builder.AddHeader("Referer", "");
builder.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36");
builder.AddHeader("Connection", "keep-alive");
builder.AddHeader("content-type", "application/json");
builder.Post(create);

OkHttpClient client = xOKHttp.NewOkHttpClient(); 
string str = client.NewCall(builder.Build()).Execute().Body().String();

XOKHttp Class

class CustomHostnameVerifier : Java.Lang.Object, IHostnameVerifier
{            
    public bool Verify(string hostname, ISSLSession session)
    {
        return true;
    }
}

class CustomX509TrustManager : Java.Lang.Object, IX509TrustManager
{
    public void CheckClientTrusted(X509Certificate[] chain, string authType)
    {
    try { }
    catch(CertificateException e) { }
}

public void CheckServerTrusted(X509Certificate[] chain, string authType)
{
    try { }
    catch (CertificateException e) { }
}

public X509Certificate[] GetAcceptedIssuers()
{
    return new X509Certificate[0];
}
}

public static OkHttpClient NewOkHttpClient()
{
try
{
    ITrustManager trustManagerArr = new CustomX509TrustManager();

    SSLContext instance = SSLContext.GetInstance("SSL");
    
    instance.Init((IKeyManager[]) null, new ITrustManager[] { trustManagerArr }, new SecureRandom());
    SSLSocketFactory socketFactory = instance.SocketFactory;
    
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    
    builder.SslSocketFactory(socketFactory, (IX509TrustManager)trustManagerArr);
    builder.HostnameVerifier(new CustomHostnameVerifier());
    builder.RetryOnConnectionFailure(false);
    return builder.Build();
}
catch (Exception e)
{
    throw new RuntimeException(e);
}
}

And RestSharp Code is:

        try
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) =>
            {
                return true;
            };
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            string userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";

            var client = new RestClient(url);
            client.UserAgent = userAgent;
            var request = new RestRequest(Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("X-Requested-With", "XMLHttpRequest");
            request.AddHeader("Referer", "");

            request.AddJsonBody(param);
            var response = await client.ExecuteTaskAsync(request);

            return response.Content;
        }
        catch (Exception ex)
        {
            string err = ex.Message;
            return err;
        }

Spent hours and hours changing parameters but nothing worked and the other problem is API owner company is not providing any assistance for .NET technology and not even disclosing what is preventing RestSharp to connect (Its a legit service not scrapping).

Any idea what preventing RestSharp to pass cloudflare validation?

0

There are 0 best solutions below