Good day Guys,
I am trying to Use an SMS API. Everything looks fine from my end but the SMS is not delivering. If i use the URL directly on Browser, it executes.
Or is anything wrong with how i built the string?
Below is the code.
Please Note tht cbo.Title is a comobox, txtFirstname is a Textbox.
public void NewText()
{
string username = "something#gmail.com";
string password = "Password";
string urlStr;
string message=" Dear " + cbo_Title.Text + " " + txt_FirstName.Text + ", Your New Savings Account Number is " + Account_No + ".Welcome to AGENTKUNLE Global Services. Your Future is Our Priority ";
string sender = "AGENTKUNLE";
string recipient=txt_Phone.Text;
urlStr = "https://portal.nigeriabulksms.com/api/?username="+username+"+password="+password+"+sender="+sender+"+message="+message+"+ mobiles="+recipient;
Uri success = new Uri(urlStr);
}
private string SendSms(string apiUrl)
{
var targetUri = new Uri(apiUrl);
var webRequest = (HttpWebRequest) WebRequest.Create(targetUri);
webRequest.Method = WebRequestMethods.Http.Get;
try
{
string webResponse;
using (var getresponse = (HttpWebResponse) webRequest.GetResponse())
{
var stream = getresponse.GetResponseStream();
if (stream != null)
using (var reader = new StreamReader(stream))
{
webResponse = reader.ReadToEnd();
reader.Close();
}
else
webResponse = null;
getresponse.Close();
}
if (!string.IsNullOrEmpty(webResponse?.Trim()))
return webResponse.Trim();
}
catch (WebException ex)
{
ErrorHelper.Log(ex);
}
catch (Exception ex)
{
ErrorHelper.Log(ex);
}
finally
{
webRequest.Abort();
}
return null;
}
You never make a request.
The Uri object is just a container for the uri (see Microsoft Docs).
Check out the HttpClient class if you want to send a request.
Related
I implemented the MS Translator API a C# console app.
My subscription level is a premium pay account, NOT the free level.
Each time I begin calling it, the first 1-5 translations work fine.
After that I get and endless stream of 400 (Bad Request) exceptions.
Here is the text response I'm getting:
Response Text: TranslateApiException Method: Translate() Message:
Cannot find an active Azure Market Place Translator Subscription
associated with the request credentials.message
id=3832.V2_Rest.Translate.117038D9
What am I missing? I am most definitely including the app id and secret key in the code?
Am I intended to also provide some additional credentials?
Here is my Translator class:
Any ideas?
// --------------------------------------------------------------------
public class Translator
{
private string AccessToken;
private DateTime TokenExpirationDate;
// ----------------------------------------------------------------
public Translator()
{
AccessToken = "";
TokenExpirationDate = new DateTime(2000, 1, 1);
}
// --------------------------------------------------------------
public void GetAccessToken()
{
if (AccessToken != "" && DateTime.Now < TokenExpirationDate)
{
Console.WriteLine("Translator: usng existing token");
return;
}
AccessToken = "";
string clientID = "<-removed->";
string clientSecret = "<-also-removed->";
String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
String strRequestDetails =
string.Format("grant_type=client_credentials&client_id={0}&client_secret={1} &scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID),
HttpUtility.UrlEncode(clientSecret));
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
webRequest.ContentLength = bytes.Length;
using (System.IO.Stream outputStream = webRequest.GetRequestStream())
{
outputStream.Write(bytes, 0, bytes.Length);
}
WebResponse webResponse = null;
try
{
webResponse = webRequest.GetResponse();
}
catch (Exception ex)
{
AccessToken = "";
Console.WriteLine("Exception: " + ex.Message);
}
if (webResponse != null)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));
AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
AccessToken = token.access_token;
TokenExpirationDate = DateTime.Now.AddSeconds(Convert.ToDouble(token.expires_in));
if (AccessToken.Length > 0) Console.WriteLine("Translator: got an access token.");
}
}
// -------------------------------------------------------------------
public string Translate(string textToTranslate, string destLanguageCode)
{
Console.WriteLine("Translator(" + destLanguageCode + "):" + textToTranslate);
string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(textToTranslate) + "&from=en&to=" + destLanguageCode;
System.Net.WebRequest translationWebRequest = System.Net.WebRequest.Create(uri);
translationWebRequest.Headers.Add("Authorization", "Bearer " + AccessToken);
System.Net.WebResponse response = null;
try
{
response = translationWebRequest.GetResponse();
}
catch (Exception ex)
{
Console.WriteLine("Translator: Fail: " + ex.Message);
Console.WriteLine("Exception: " + ex.Message);
}
if (response != null)
{
System.IO.Stream stream = response.GetResponseStream();
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode);
System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument();
xTranslation.LoadXml(translatedStream.ReadToEnd());
Console.WriteLine("Translator(" + destLanguageCode + "):" + xTranslation.InnerText);
return xTranslation.InnerText;
}
return "";
}
}
// ------------------------------------------------------------------------
public class AdmAccessToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public string expires_in { get; set; }
public string scope { get; set; }
}
}
Look at the content of the response. It will contain the cause of the error in human-readable form.
It is likely that you do not have a subscription associated with the credentials of your request. To fix that:
Visit https://datamarket.azure.com/account/datasets and make sure you have a subscription to "Microsoft Translator - Text Translation".
Visit https://datamarket.azure.com/developer/applications and define a client ID and password.
Use that client ID and password in your application.
I have a API which returns the json response.
When I call the API from Fiddler it gives me the json reponse
as shown below:
JSON Response:
Call to API from Web page:
protected void FinalCall()
{
// try
// {
string url = txtdomainURL.Text.Trim();
string apiname = txtAPIname.Text.Trim();
string apiURL = apiname+"/"+txtStoreID.Text.Trim()+"/"+txtSerialNo.Text.Trim(); //"duediligence/1/45523354232323424";// 990000552672620";//45523354232323424";
//duediligence/1/45523354232323424 HTTP/1.1
string storeID = txtStoreID.Text.Trim();//Test Store ID:1 Live Store ID: 2
string partnerID = txtPartnerID.Text.Trim();// "1";
string scretKey = txtSecretKey.Text.Trim();// "234623ger787qws3423";
string requestBody = txtRequestBody.Text.Trim(); //"{\"category\": 8}";
string data = scretKey + requestBody;
string signatureHash = SHA1HashStringForUTF8String(data);
lblSignatureHash.Text = signatureHash;
String userName = partnerID;
String passWord = signatureHash;
string credentials = userName + ":" + passWord;//Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
var dataString = JsonConvert.SerializeObject(requestBody); //JsonConvert.SerializeObject(requestBody);
var bytes = Encoding.Default.GetBytes(dataString);
WebClient client = new WebClient();
string base64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
client.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
lblBase64.Text = base64;
client.Headers.Add(HttpRequestHeader.Accept, "application/json");
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
//string response = cli.UploadString(url + apiURL, dataString); //"{some:\"json data\"}"
string completeURLRequest = url + apiURL;
//I GET ERROR HERE
var result = client.DownloadString(completeURLRequest);
//CODE below this line is not executed
//Context.Response.TrySkipIisCustomErrors = true;
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = serializer.DeserializeObject(result.ToString());
//var result1 = client.UploadData(completeURLRequest, "POST", bytes);
Response.Write(result);
txtwebresponse.Text = jsonObject.ToString();
//}
Now, When the same is executed from a web page it throws exeception '401 Unauthorized Exception'. So, instead of showing error page I want to read the returned JSON error response (as in fiddler) and show to user.
Help Appreciated!
Adapted from this answer to ".Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned" by Jon Skeet:
try
{
using (WebResponse response = request.GetResponse())
{
Console.WriteLine("You will get error, if not do the proper processing");
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse) response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
// text is the response body
string text = reader.ReadToEnd();
}
}
}
Slightly changing SilentTremor's answer. Combining the using statements makes the code a little bit shorter.
catch (WebException ex)
{
HttpWebResponse httpResponse = (HttpWebResponse)ex.Response;
using (WebResponse response = ex.Response)
using (Stream data = response.GetResponseStream())
using (StreamReader reader = new StreamReader(data))
{
string errorMessage = reader.ReadToEnd();
}
}
I am trying to access to some rest services of a specific web server for my WP8 app and I canĀ“t do it well. For example, this is the code that I use when I try to login the user. I have to pass a string that represents a Json object ("parameters") with the username and the password and the response will be a json object too. I can't find the way to pass this pasameters in the rest request.
This is the code;
public void login(string user, string passwrd)
{
mLoginData.setUserName(user);
mLoginData.setPasswd(passwrd);
string serviceURL = mBaseURL + "/service/user/login/";
string parameters = "{\"username\":\"" + mLoginData.getUserName() + "\",\"password\":\"" + mLoginData.getPasswd() + "\"}";
//MessageBox.Show(parameters);
//MessageBox.Show(serviceURL);
//build the REST request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceURL);
request.ContentType = "application/json";
request.Method = "POST";
//async request launchs "Gotresponse(...) when it has finished.
request.BeginGetResponse(new AsyncCallback(GotResponse), request);
}
private void GotResponse(IAsyncResult ar)
{
try
{
string data;
// State of request is asynchronous
HttpWebRequest myHttpWebRequest = (HttpWebRequest)ar.AsyncState;
using (HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(ar))
{
// Read the response into a Stream object.
Stream responseStream = response.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
}
}
catch (Exception e)
{
string exception = e.ToString();
throw;
}
}
I tried too with the webClient and the httpClient classes too but without any result.
Thanks and sorry for my bad english.
I solved it with the HttpClient class. This is the code.
public async void login(string user, string passwrd)
{
string serviceURL = "";
string parameters = "";
HttpClient restClient = new HttpClient();
restClient.BaseAddress = new Uri(mBaseURL);
restClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, serviceURL);
req.Content = new StringContent(parameters, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
string responseBodyAsText = "";
try
{
response = await restClient.SendAsync(req);
response.EnsureSuccessStatusCode();
responseBodyAsText = await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException e)
{
string ex = e.Message;
}
if (response.IsSuccessStatusCode==true)
{
dynamic data = JObject.Parse(responseBodyAsText);
}
else
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
MessageBox.Show("User or password were incorrect");
}
else
{
MessageBox.Show("NNetwork connection error");
}
}
}
I wasn't setting the header values of the request correctly.
I hope this can help someone.
I am encountering a problem getting the access_token in client application using oauth.
The returned response has empty body though in API I can see the response is not empty.
tokenresponse = {
"access_token":"[ACCESSTOKENVALUE]",
"token_type":"bearer",
"expires_in":"1200",
"refresh_token":"[REFRESHTOKENVALUE]",
"scope":"[SCOPEVALUE]"
}
The method from API that returns the token http://api.sample.com/OAuth/Token:
public ActionResult Token()
{
OutgoingWebResponse response =
this.AuthorizationServer.HandleTokenRequest(this.Request);
string tokenresponse = string.Format("Token({0})", response!=null?response.Body:""));
return response.AsActionResult();
}
The client method that requests the token is:
public string GetAuthorizationToken(string code)
{
string Url = ServerPath + "OAuth/Token";
string redirect_uri_encode = UrlEncode(ClientPath);
string param = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Remove(HttpRequestHeader.Cookie);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
if (!string.IsNullOrEmpty(result))
{
TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
return UpdateAuthorizotionFromToken(tokendata);
}
return null;
}
The result variable is empty.
Please let me know if you have any idea what could cause this. Initially I assumed is because of the cookies so I tried to remove them from request.
Thanks in advance.
Dear just create webclient using following code and you will get json info in tokeninfo.I used it and simply its working perfect.
WebClient client = new WebClient();
string postData = "client_id=" + ""
+ "&client_secret=" + ""
+ "&grant_type=password&username=" + "" //your username
+ "&password=" + "";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
You can then use substring that contains only token from tokeninfo.
To upload tracks on sound cloud.
private void TestSoundCloudupload()
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "Some title");
form.Add("track[sharing]", "public");
form.Add("oauth_token", "");
form.Add("format", "json");
form.Add("Filename", "0.mp3");
form.Add("Upload", "Submit Query");
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
Edited my code to use WebClient...still doesnt work
string hhtmlurl = /Thumbnail.aspx?productID=23&Firstname=jimmy&lastnight=smith;
string strFileName = string.Format("{0}_{1}", hfUserID.Value, Request.QueryString["pid"].ToString() + documentID.ToString());
WebClient client = new WebClient();
client.DownloadFile("http://www.url.ca/" + hhtmlurl.Value + "card=1", strFileName);
Try this method. This will give you string return for the entire html content. Write this string in whatever file you want
public string GetHtmlPageContent(string url)
{
HttpWebResponse siteResponse = null;
HttpWebRequest siteRequest = null;
string content= string.Empty;
try
{
Uri uri = new Uri(url);
siteRequest = (HttpWebRequest)HttpWebRequest.Create(url);
siteResponse = (HttpWebResponse)siteRequest.GetResponse();
content = GetResponseText(siteResponse);
}
catch (WebException we)
{
// Log error
}
catch (Exception e2)
{
// Log error
}
return content;
}
public string GetResponseText(HttpWebResponse response)
{
string responseText = string.Empty;
if (response == null)
return string.Empty;
try
{
StreamReader responseReader = new StreamReader(response.GetResponseStream());
responseText = responseReader.ReadToEnd();
responseReader.Close();
}
catch (Exception ex)
{
// Log error
}
return responseText;
}
Hope this will help you.
WebClient.DownloadFile would probably be easier.
Instead of FileStream, use the WebClient class, which offers the delightfully simple DownloadFile() method:
WebClient client = new WebClient();
client.Downloadfile("http://www.url.ca/" + hhtmlurl + "card=1", strFileName);