I am not able to get the friends list from the facebook graph api.
it is throwing exception the Bad request.
https://graph.facebook.com/me/friends?access_token="accessTokenString";
here is my code
public IDictionary<string, string> GetUserData(string accessCode, string redirectURI)
{
string token = GetHTML(Facebook_GraphAPI_Token + "client_id=" + AppID + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectURI) + "%3F__provider__%3Dfacebook" + "&client_secret=" + AppSecret + "&code=" + accessCode);
if (token == null || token == "")
{
return null;
}
string friendsData = Web.GetHTML(Facebook_GraphAPI_Friends + "fields=id,first_name,last_name,name,email,username,gender,link,bio,birthday,friendlists,friends&access_token=" + token.Substring("access_token=", "&"));
//string substringToken=token.Substring("access_token=", "&");
//string friendsData = Web.GetHTML(Facebook_GraphAPI_Friends + substringToken);
return friendsData ;
}
public static string GetHTML(string URL)
{
string connectionString = URL;
try
{
System.Net.HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(connectionString);
myRequest.Credentials = CredentialCache.DefaultCredentials;
//// Get the response
WebResponse webResponse = myRequest.GetResponse();
Stream respStream = webResponse.GetResponseStream();
////
StreamReader ioStream = new StreamReader(respStream);
string pageContent = ioStream.ReadToEnd();
//// Close streams
ioStream.Close();
respStream.Close();
return pageContent;
}
catch (Exception)
{
}
return null;
}
I have found wrong fields in friends request api
friendlists,friends please remove these fields
Correct End Point
https://graph.facebook.com/me/friends?fields=id,first_name,last_name,name,email,username,gender,link,bio,birthday&access_token={your facebook access token}
Related
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.
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'm trying to get a http response from a web server which asks for my credentials in application/json. Although on their website they say I have to use POST Request, I get 405 HTTP status and a WebException as an answer. Here is my code:
private bool RunAuth(bool b, String user, String pass)
{
if(b)
{
HttpWebRequest h = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/");
h.Method = "POST";
h.KeepAlive = false;
h.ContentType = "application/json";
String json = "{" + "\"agent\": {" + "\"name\": \"Minecraft\"," + "\"version\": 1" + "}," + "\"username\": \""+user+"\"," + "\"password\": \""+pass+"\"," + "\"clientToken\": \"" + tokenGenerated + "\"" + "}"; //tokenGenerated = Guid.NewGuid().ToString();
h.ContentLength = json.Length;
using(var stream = new StreamWriter(h.GetRequestStream()))
{
stream.Write(json);
stream.Flush();
stream.Close();
}
HttpWebResponse r = (HttpWebResponse)h.GetResponse();
using (var stream = new StreamReader(r.GetResponseStream()))
{
String result = stream.ReadToEnd();
File.WriteAllText(appdata + #"\.craftunio\authtest.txt", result);
}
return true;
}
else
{
return false;
}
}
You are calling the wrong endpoint. You should call
HttpWebRequest h = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/authenticate");
I would like to try upload a mp3 file to my soundcloud account. I have written this code for this job.
WebClient client = new WebClient();
string postData = "client_id=" + "xxxxx"
+ "&client_secret=" + "xxx"
+ "&grant_type=password&username=" + "xxx" //your username
+ "&password=" + "xxx";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
tokenInfo = tokenInfo.Remove(0, tokenInfo.IndexOf("token\":\"") + 8);
string token = tokenInfo.Remove(tokenInfo.IndexOf("\""));
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
request.CookieContainer = new CookieContainer();
//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(filePath, "#/" + filePath, "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "biksad");
form.Add("track[sharing]", "public");
form.Add("oauth_token", token);
form.Add("format", "json");
form.Add("Filename", fileName);
form.Add("Upload", "Submit Query");
string lblInfo;
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
lblInfo = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
lblInfo = ex.ToString();
}
}
When I debug this code part. I get (422) Unprocessable Entity error in catch block. Why I get this error? How can solve this problem?
Check the Soundcloud documentation:
http://developers.soundcloud.com/docs#errors
422 - "The request looks alright, but one or more of the parameters looks a little screwy. It's possible that you sent data in the wrong format (e.g. an array where we expected a string)."
I wonder if someone can give me some pointers on using the linked in API. I thought I had it sussed but for some reason when trying to get the auth_token I just get http 400 Bad Request.
My code, simply is:
public string redirectUrl = URLTOREDIRECT;
public String apiKey = APIKEY;
public String apiSecret = APISECRET;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["code"] != null)
{
VerifyAuthentication(Request.QueryString["code"]);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=apiKey&scope=rw_company_admin&state=DCEEFWF45453sdffef424&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl));
}
public String VerifyAuthentication(string code)
{
string authUrl = "https://www.linkedin.com/uas/oauth2/accessToken";
var sign = "grant_type=authorization_code" + "&code=" + code + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + _consumerkey + "&client_secret=" + _consumerSecret;
// var postData = String.Format("grant_type=authorization_code&code={0}&redirect_uri={1}&client_id={2}&client_secret={3}", code, HttpUtility.HtmlEncode(redirectUrl), apiKey, apiSecret);
HttpWebRequest webRequest = WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
webRequest.Method = "POST";
//This "application/x-www-form-urlencoded"; line is important
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = sign.Length;
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(sign);
requestWriter.Close();
StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
return responseReader.ReadToEnd().ToString() ;
}
The code is all in the same page for testing purposes and is the same page as the redirectUrl.
Really stumped, tried all variations.
First bit clearly works as I get directed to linked in to allow app. The second part getting the auth token fails.
After much head scratching, eureka moment - did not need to send the info in the request.
string authUrl = "https://www.linkedin.com/uas/oauth2/accessToken";
var sign = "grant_type=authorization_code&code=" + HttpUtility.UrlEncode(code) + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + apiKey + "&client_secret=" + apiSecret;
//byte[] byteArray = Encoding.UTF8.GetBytes(sign);
HttpWebRequest webRequest = WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = webRequest.GetRequestStream();
String postData = String.Empty;
byte[] postArray = Encoding.ASCII.GetBytes(postData);
dataStream.Write(postArray, 0, postArray.Length);
dataStream.Close();
WebResponse response = webRequest.GetResponse();
dataStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(dataStream);
String returnVal = responseReader.ReadToEnd().ToString();
responseReader.Close();
dataStream.Close();
response.Close();
return returnVal;
I'm Using this code and it's working fine..... C# code ASP.NET :
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LI
{
public partial class WebForm3 : System.Web.UI.Page
{
public string redirectUrl = "http://localhost:64576/WebForm3";
public string TokenGlobe = "";
public String apiKey = "API_KEY";
public string retval = "";
public String apiSecret = "API_Secret";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["code"] != null)
{
VerifyAuthentication(Request.QueryString["code"]);
}
}
}
protected void btnTwit_Click(object sender, EventArgs e)
{
var Address = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=" + apiKey + "&redirect_uri=http://localhost:64576/WebForm3&state=987654321&scope=w_share";
using (var webClient = new WebClient())
{
webClient.Headers.Add("x-li-format", "json");
}
Response.Redirect(Address);
}
public String VerifyAuthentication(string code)
{
string authUrl = "https://www.linkedin.com/oauth/v2/accessToken";
var sign1 = "grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirectUrl + "&client_id=" + apiKey + "&client_secret=" + apiSecret + "";
var sign = "grant_type=authorization_code&code=" + HttpUtility.UrlEncode(code) + "&redirect_uri=" + HttpUtility.HtmlEncode(redirectUrl) + "&client_id=" + apiKey + "&client_secret=" + apiSecret;
HttpWebRequest webRequest = System.Net.WebRequest.Create(authUrl + "?" + sign) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.Host = "www.linkedin.com";
webRequest.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = webRequest.GetRequestStream();
String postData = String.Empty;
byte[] postArray = Encoding.ASCII.GetBytes(postData);
dataStream.Write(postArray, 0, postArray.Length);
dataStream.Close();
WebResponse response = webRequest.GetResponse();
dataStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(dataStream);
String returnVal = responseReader.ReadToEnd().ToString();
responseReader.Close();
dataStream.Close();
response.Close();
var stri = redirectUrl;
retval = returnVal.ToString();
var objects = JsonConvert.DeserializeObject<Accountdsdsd>(retval);//JArray.Parse(retval);
TokenGlobe = objects.access_token;
var SentStatus = PostLinkedInNetworkUpdate(TokenGlobe, "Hello API"); //Share
return TokenGlobe;
// return responseReader.ReadToEnd().ToString();
}
private string linkedinSharesEndPoint = "https://api.linkedin.com//v1/people/~/shares?oauth2_access_token={0}&format=json";
private const string defaultUrl = "http://localhost:64576/WebForm3";
private const string defaultImageUrl = "http://opusleads.com/opusing/technology/technology%20(1).jpg"; //Image To Post
public bool PostLinkedInNetworkUpdate(string accessToken, string title, string submittedUrl = defaultUrl, string submittedImageUrl = defaultImageUrl)
{
var requestUrl = String.Format(linkedinSharesEndPoint, accessToken);
var message = new
{
comment = "Testing out the LinkedIn Share API with JSON",
content = new Dictionary<string, string>
{ { "title", title },
{ "submitted-url", submittedUrl },
{"submitted-image-url" , submittedImageUrl}
},
visibility = new
{
code = "anyone"
}
};
var requestJson = new JavaScriptSerializer().Serialize(message);
var client = new WebClient();
var requestHeaders = new NameValueCollection
{
{"Content-Type", "application/json" },
{"x-li-format", "json" }
};
client.Headers.Add(requestHeaders);
var responseJson = client.UploadString(requestUrl, "POST", requestJson);
var response = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(responseJson);
return response.ContainsKey("updateKey");
}
}
//Json Parsing
public class Accountdsdsd
{
public string access_token { get; set; }
public string expires_in { get; set; }
}
}