I want make outbound calls from my console application using C# With Twilio voice api. But most of the time i am getting the connection error message. My system is using the proxy server. So i want to add proxy authentication with the code. Please suggest.
My code is as below :
const string accountSid = "*****************";
const string authToken = "*****************";
var client = new TwilioRestClient(accountSid, authToken); TwilioClient.Init(accountSid, authToken);
var to = new PhoneNumber("*****************");
var from = new PhoneNumber("*****************"); `enter code here`
var call = CallResource.Create(to, from, url: new Uri(tempURL));
Twilio Evangelist here.
If you're trying to use the proxy here, I think using our Rest API is going to be helpful. Try this code below to hook your proxy server up to the HttpClient object:
public static HttpClient GetProxy()
{
// First create a proxy object
var proxyUri = $"{proxyServerSettings.Address}:{proxyServerSettings.Port}";
var proxyCreds = new NetworkCredential("proxyuser", "proxypassword");
var proxy = new WebProxy(proxyUri, false)
{
UseDefaultCredentials = false,
Credentials = proxyCreds,
};
// Now create a client handler which uses that proxy
var httpClientHandler = new HttpClientHandler()
{
Proxy = proxy,
PreAuthenticate = true,
UseDefaultCredentials = false,
};
return new HttpClient(httpClientHandler);
}
To make the telephone call with the proxy, you can use the sample code here:
const string accountSid = "*****************";
const string authToken = "*****************";
string to = "+1xxxxxxxxxx";
string from = "+1xxxxxxxxxx";
string callUrl = $"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Calls";
var httpClient = GetProxy();
var authorizationValue = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{accountSid}:{authToken}"));
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Basic {authorizationValue}");
var result= httpClient.PostAsync(callUrl, new FormUrlEncodedContent(new Dictionary<string,string>
{
{"To", to},
{"From", from},
{"Url", "http://demo.twilio.com/docs/voice.xml"}
}));
Let me know if this helps or if you run into additional problems. Happy to help here
Related
I'm experiencing an intermittent problem with our SharePoint 2010 REST API. I have a .Net Core Console application that makes a series of calls to SharePoint List Endpoints to get a JSON response. My problem is that at random times, the API response is an error page:
A relative URI cannot be created because the 'uriString' parameter
represents an absolute URI.http://www.example.com/somefolder/file.svc
Is there a problem with my HTTPClient configuration? Is there a configuration setting that I can toggle in SharePoint to prevent the error or more reliable?
var uri = new Uri("http://www.example.com/");
var credential = new NetworkCredential("username", "password", "domain");
var credentialsCache = new CredentialCache { { uri, "NTLM", credential } };
var handler = new HttpClientHandler { Credentials = credentialsCache };
HttpClient Client = new HttpClient(handler);
Client.BaseAddress = new Uri("http://www.example.com/sharepoint/path/ListData.svc/");
// Make the list request
var result = await Client.GetAsync("MySharePointList");
To get the list items, the REST API URI like below.
http://sp2010/_vti_bin/ListData.svc/listname
Modify the code as below.
var siteUrl = "http://www.example.com/";
var listName = "MySharePointList";
var uri = new Uri(siteUrl);
var credential = new NetworkCredential("username", "password", "domain");
var credentialsCache = new CredentialCache { { uri, "NTLM", credential } };
var handler = new HttpClientHandler { Credentials = credentialsCache };
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri(uri, "/_vti_bin/ListData.svc");
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json;odata=verbose");
var requestURL = siteUrl + "/_vti_bin/ListData.svc/" + listName;
// Make the list request
var result = client.GetAsync(requestURL).Result;
var items= result.Content.ReadAsStringAsync();
I'm trying to call the Shopware REST API from c#. Shopware has documentation for calling the API using curl, and mostly I can convert this to c# and HttpClient, but for some options I just don't know what headers to set:
The Shop is behind a basic htaccess-auth and has the Shopware auth using an apikey. My code so far:
var handler = new System.Net.Http.HttpClientHandler { Credentials = new NetworkCredential(htaccessUsername, htaccessPassword) });
var client = new System.Net.Http.HttpClient(handler);
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl + "orders?limit=20"))
{
var encodedStr = Convert.ToBase64String(Encoding.Default.GetBytes($"{username}:{apiKey}"));
var authorizationKey = "Basic" + " " + encodedStr;
requestMessage.Headers.Add("Authorization", authorizationKey);
// curl_setopt($this->cURL, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($this->cURL, CURLOPT_FOLLOWLOCATION, false);
// curl_setopt($this->cURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
// curl_setopt(
// $this->cURL,
// CURLOPT_HTTPHEADER,
// ['Content-Type: application/json; charset=utf-8']
// );
using (var responseMessage = await client.SendAsync(requestMessage))
{
var data = await responseMessage.Content.ReadAsStringAsync();
System.Diagnostics.Trace.WriteLine(data);
}
}
Basic htaccess auth is working, but the Shopware auth does fail with the following response in data:
"{\"success\":false,\"message\":\"Invalid or missing auth\"}"
I guess I Need to somehow achieve curl_setopt($this->cURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); in c#, but I found no clue how to convert These curl options to a header.
Any help?
Looks like the answer for you is here:
var credCache = new CredentialCache();
var basicCred = new NetworkCredential(htaccessUsername, htaccessPassword);
var digestCred = new NetworkCredential(username, apiKey);
credCache.Add(new Uri("http://.com/"), "Basic", basicCred);
credCache.Add(new Uri("http://.com/"), "Digest", digestCred);
var httpClient = new HttpClient(new HttpClientHandler { Credentials = credCache });
I am trying to pull REST data from an API but I need to handle the calls to the API with some server side solution. I have tried using the following code
try
{
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(60);
var request = new HttpRequestMessage()
{
RequestUri = new Uri(string.Format("https://jsonodds.com/{0}{1}{2}", "api/odds/", "?source=", "3")),
Method = HttpMethod.Get,
};
request.Headers.Add("JsonOdds-API-Key", "your key");
HttpResponseMessage response = client.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
String.Format("Success");
}
}
catch (Exception ex)
{ //log error }
I receive a 407() error. Any ideas or tips how to do this?
If you are going through a proxy server then you need to use a different constructor for HttpClient.
_httpClient = new HttpClient(new HttpClientHandler
{
UseProxy = true,
Proxy = new WebProxy
{
Address = new Uri(proxyUrl),
BypassProxyOnLocal = false,
UseDefaultCredentials = true
}
})
{
BaseAddress = url
};
Replace proxyUrl with your proxy address then replacing the credential with those that are valid for your proxy. This example uses the default credentials, but you can pass a NetworkCredential to the WebProxy.
I am using the HttpClient class to make GET requests, it works perfectly without proxy, but when I try to make a request thought a proxy server, it adds hostname in the path and there is also hostname in headers, so the full url is like http://google.comhttp://google.com/
The code:
static void GetSmth()
{
var baseAddr = new Uri("http://google.com");
var handler = new HttpClientHandler
{
AllowAutoRedirect = false,
UseCookies = true,
UseProxy = true,
Proxy = new WebProxy("111.56.13.168:80", true),
};
HttpClient client = new HttpClient(handler);
client.BaseAddress = baseAddr;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "/");
var resp = client.SendAsync(request).Result;
}
Wireshark screenshot:
What is wrong with it?
I have the following code in C# that uses HTTPClient and I am trying to migrate to RestSharp to leverage the nice Derserialization code
here is my current code:
var httpClient = new HttpClient(new HttpClientHandler()
{
UseDefaultCredentials = true,
AllowAutoRedirect = false
});
var response = httpClient.GetStringAsync(myUrl).Result;
Here is the equivalent code using restsharp:
_client = new RestClient { BaseUrl =new Uri(myUrl) };
var request = new RestRequest { Method = method, Resource = "/project", RequestFormat = DataFormat.Json };
var response = _client.Execute(request);
but I can't figure out how to set
UseDefaultCredentials = true
and
AllowAutoRedirect = false
on the restSharp side. Is this supported?
You need provide the basic authentication information like below for RestSharp if you want to use the Basic HTTP authentication.
_client = new RestClient { BaseUrl =new Uri(myUrl) };
_client.Authenticator = new HttpBasicAuthenticator("<username>", "<password>");
To use the windows authentication:
Update:
const Method httpMethod = Method.GET;
string BASE_URL = "http://localhost:8080/";
var client = new RestClient(BASE_URL);
// This property internally sets the AllowAutoRedirect of Http webrequest
client.FollowRedirects = true;
// Optionally you can also add the max redirects
client.MaxRedirects = 2;
var request = new RestRequest(httpMethod)
{
UseDefaultCredentials = true
};
client.Execute(request);