I want to make a short app that can post on my Facebook wall(timeline).
My app is based on webview component (QWebView) to obtain the access token for publish stream
I can take the access token but when I try to post something, on my Facebook nothing appears.
void MainWindow::on_pushButton_clicked(){
QUrl url("https://www.facebook.com/dialog/oauth");
url.addQueryItem("client_id","my_app_id");
url.addQueryItem("redirect_uri","https://www.facebook.com/connect/login_success.html");
url.addQueryItem("response_type","token");
url.addQueryItem("scope","read_stream,publish_stream");
MainWindow::browser->load(url);
MainWindow::browser->show();
}
void MainWindow::on_browser1_loadFinished(bool arg1)
{
QUrl url= browser->url();
QString strUrl = url.toString();
qDebug()<<"URL: "<<strUrl;
if( strUrl.contains(QString("access_token="), Qt::CaseSensitive)){
int sIndex = strUrl.indexOf("access_token=");
int eIndex = strUrl.indexOf("&expires_in");
QString mAccessToken= strUrl.mid(sIndex, eIndex - sIndex);
mAccessToken = mAccessToken.remove("access_token=");
qDebug()<<"TOKEN: + "<<mAccessToken;
QUrl params;
params.addQueryItem("access_token",mAccessToken);
params.addQueryItem("message","TEST !!");
params.addQueryItem("link","https://young-day-9284.herokuapp.com/");
params.addQueryItem("description","Testing");
params.addQueryItem("name","Test ");
params.addQueryItem("caption","Testing");
qDebug()<<"Mesajul trimis: "<<QString(params.encodedQuery());
QNetworkAccessManager mNetManager(this);
QNetworkRequest request(QUrl("https://graph.facebook.com/me/feed"));
//request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
mNetManager.post(request,params.toString(QUrl::None).toAscii());
}
}
Using WebKit for this sort of program is overkill. WebKit is a full web engine and is a quite heavy component in terms of memory usage and complexity.
Try to have a look at the various OAuth implementations that exist for Qt already. For example this: https://github.com/ayoy/qoauth
QOauth even ships with some example code in the doc directory.
From Qt doc:
void QUrl::addQueryItem ( const QString & key, const QString & value ):
Note: This method does not encode spaces (ASCII 0x20) as plus (+) signs, like HTML forms do. If you need that kind of encoding, you must encode the value yourself and use QUrl::addEncodedQueryItem.
or don't use spaces.
Related
I am using Unity 5.5.2f1 pro and facebook's SDK v 7.9.4
I have a script which after login (managed in a previous scene) sends an API request to FB asking for friends, name and email and sends that info as a POST to a php website.
code:
[Serializable]
public struct FBData {
public string first_name;
public string email;
public string friends;
public string id;}
public class UserManagement : MonoBehaviour {
string urlSaveUserData="some php website";
public Text testTxt;
FBData parsedData;
// Use this for initialization
void Start () {
//Check if it's the first time the user is opening the app.
if (UserInfo.FIRST_TIME) {
//update text (only used for testing, should be removed in production.)
testTxt.text = "Your user id is: " + UserInfo.ID;
//Perform FB.API call to get User Data.
getUserData ();
//Save in SQL table. (won't get here if line in getUserData() is active)
StartCoroutine ("saveUserData");
} else {
//do something else.
}
note: Since this is meant for iOS I have to test it on a device so I'm using text in the screen to display info (think of it as a badly implemented print statement).
The problem: In my callback function for FB.API I write in the text Gameobject (aka testTxt) the parsed information from the response which is saved in the Custom UserInfo clss. It display's correctly but the code gets stuck there. It doesn't continue to the next function. HOWEVER, if I delete/comment that line and don't display anything in the text field. The codes does continue to the POST function BUT the information from the API call is not passed, i.e my custom class is empty (leading me to believe the callback function is not called at all).
public void getUserData(){
string query = "me?fields=first_name,email,friends";
FB.API (query, HttpMethod.GET, Apicallback, new Dictionary<string, string> ());
}
private void Apicallback(IGraphResult result){
//Parse Graph response into a specific class created for this result.
parsedData = JsonUtility.FromJson<FBData>(result.RawResult);
//Pass each field into UserInfo class.
UserInfo.EMAIL = parsedData.email;
UserInfo.FRIENDS = parsedData.friends;
UserInfo.NAME = parsedData.first_name;
UserInfo.FACEBOOKID = parsedData.id;
/*problem area, if I comment line below, then previous information is apparently not stored. If left as is then testTxt displays correct information but code gets stuck there. */
testTxt.text = "This is the info from USerInfoInside the APICallback: " + UserInfo.EMAIL + UserInfo.FRIENDS + UserInfo.FACEBOOKID;
}
The function below is to send info to php website, is there for illustrative purposes:
code:
public IEnumerator saveUserData() {
//get user info (this information is EMPTY if line in getUserData() is commented.
parsedData.id = UserInfo.FACEBOOKID;
parsedData.friends = UserInfo.FRIENDS;
parsedData.first_name = UserInfo.NAME;
parsedData.email = UserInfo.EMAIL;
//translate data into json
string JsonBodyData = JsonUtility.ToJson (parsedData);
//Custom web request (POST method doesnt seem to work very well, documentation example sends empty form)
var w = new UnityWebRequest(urlSaveUserData, "POST");
byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(JsonBodyData);
w.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
w.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
w.SetRequestHeader("Content-Type", "application/json");
yield return w.Send();
//work with received data...}
Im stuck here any help is appreciated. Thanks!
Be sure to use EscapeURL when using strings directly for JSON or HTTP POST and GET methods. The lack of this treatment tends to screw things over, particulary in iOS platforms.
From what I can see, this code
string query = "me?fields=first_name,email,friends";
should instead be escaped as
string query = WWW.EscapeURL("me?fields=first_name,email,friends");
so characters like "?" won't get encoded as an URL symbol.
I'm assuming you don't need to do that for your illustrative example, because UnityWebRequest already escapes your POST request strings internally, but I can't fully confirm that.
I realize that there are other posts asking similar questions, but do not quite answer the question I have. I apologize if this is not enough info, formatting is off, or whatnot. Its my first time posting.
Basically my group is doing an iPhone app that needs to interface with our sql server database. But because they can't talk directly with eachother we are implementing an asp.net medium that will accept XML and apparently will need to output JSOD. Currently I have a .asmx written with "working" code (test string inside code). Right now I am just trying to accept the XML from the iPhone. I feel like we are missing something either on his end (iPhone) or my end (.asmx). Hopefully you bright minds out there can fill me in because with our combined research....i feel theres something missing. Maybe im wrong and Ive we've got our stuff together which would be awesome.
apparently this is all he needs (according to his research) on his end in order to connect and transfer the information. obviously its not .asmx but it shouldn't matter the extension right?
NSURL *url = [NSURL URLWithString:#"http://myurl.com/RequestHandler.ashx"];
Here is the code that I have with my .asmx (note the function is where the meat is at)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml.Linq;
namespace Outbreak_Mobile
{
[WebService(Namespace = "http://OutbreakMobile.net/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod (Description="To intake an xml package from iPhone and store it")]
public string iPhoneLocation(string xml)
{
//test string to output to screen
string location = null;
//test string of xml to be parsed
//will be converting next line to parse input xml
//string xml = #"<Player>
// <Latitude>42.13245465</Latitude>
// <Longitude>11.11111111</Longitude>
// </Player>";
//line to parse document
//xdocument doc = xdocument.parse(incoming xml)
XDocument doc = XDocument.Parse(xml);
//grabs the information inside <player> tags
XElement loc = doc.Elements("Player").SingleOrDefault();
if (loc != null)
{
var lat = (double)loc.Element("Latitude");
var lng = (double)loc.Element("Longitude");
location = "Lat: " + lat + '\n' + "Long: " + lng;
}
//this is what puts out to the screen
return location;
}
}
}
currently the output of the string 'location' was just for functionality testing and will change when I know that I am receiving the packages correctly. What are we missing in order to connect with one another?
Thank you all in advance!
You created a NSURL object. Now you need to create a NSURLConnection to download the data from that URL.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
And to transfer the NSData object you got from the connection just use NSString -initWithData:encoding: method.
I am trying to download HTML content from any URL through webbrowser control in C#.net.
I choose webrowser to handle Javascript issues. I am using webbrowser control without placing
it on the form. It works great for one url, but when I call it for multiple urls I am unable
to download the page.
Here is the code
GetWebpage()
{
System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
wb.Navigate(sURI, false);
bDocumentLoaded = false;
while (!bDocumentLoaded)
{
Application.DoEvents();
Thread.Sleep(100);
}
sHTML = wb.DocumentText;
bDocumentLoaded = false;
}
Event:
private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
System.Windows.Forms.WebBrowser webBrowser1;
webBrowser1 = sender as WebBrowser;
string strTit = webBrowser1.DocumentTitle;
string str = webBrowser1.DocumentText;
bDocumentLoaded = true;
}
Cheers,
Karthik
You can use webclient object to fetch data from some url.
Try using Downloading String
public static void DownloadString (string address)
{
WebClient client = new WebClient ();
string reply = client.DownloadString (address);
Console.WriteLine (reply);
}
You can also use ASYC method of same downloading string.
I think your problem is that some sites are detecting specific browsertype and then they are returning HTML
Try setting the HeaderProperty of WebClient Object this is a list of HttpWebRequest Object
For Example
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
Modify the useragent of HTTPWEBRequest then add to headers.
HTTPWEBRequest.UserAgent=".NET Framework Test Client";
You can check more information about this in MSDN Link
I might recommend using the mshtml and SHDocVW libraries and using approach found in the answer here:
Unable to to locate and click a submit button using mshtml.HTMLInputElement
Currently I'm working on my HTML 5 ASP.Net Application,
Which has requirement of Graffiti Wall, When user draw something on my Wall(means on my HTML 5 Canvas element), and Press Share Button on my Page, at that time the whole picture should need to be post on one of the Facebook Page.
Now my question is that is this thing possible using C# facebook sdk by codeplex ?
if its possible, than how to post image on facebook fan page using this SDK??
Where can I get the good resource the implement this kind of functionality or similar code.
I've check the all examples given by them, there is no any example which post on the facebook fan page.
Or even other library that can implement this kind of functionality.
I've check this library, and see that it has FacebookClient,ExpandoObject, FacebookMediaObject kind of classes, but how to and where to use this classes,where are the description and sample code.
Thanks,
Jigar Shah
you can post to others wall using "{id}/feed"
if you want to post image/video on wall. Try downloading the samples from nuget.
Install-Package Facebook.Sample
Here is how to do using the graph api.
public static string UploadPictureToWall(string id, string accessToken, string filePath)
{
var mediaObject = new FacebookMediaObject
{
FileName = System.IO.Path.GetFileName(filePath),
ContentType = "image/jpeg"
};
mediaObject.SetValue(System.IO.File.ReadAllBytes(filePath));
try
{
var fb = new FacebookClient(accessToken);
var result = (IDictionary<string, object>)fb.Post(id + "/photos", new Dictionary<string, object>
{
{ "source", mediaObject },
{ "message","photo" }
});
var postId = (string)result["id"];
Console.WriteLine("Post Id: {0}", postId);
// Note: This json result is not the orginal json string as returned by Facebook.
Console.WriteLine("Json: {0}", result.ToString());
return postId;
}
catch (FacebookApiException ex)
{
// Note: make sure to handle this exception.
throw;
}
}
I've just found a great sample of Facebook Connect on Blackberry by Eki Y. Baskoro,
The following is a short HOWTO on using Facebook Connect on Blackberry. I created a simple Facade encapsulating the Facebook REST API as well as added 'rough' MVC approach for screen navigation. I have tested on JDE 4.5 using 8320 simulator. This is still work in progress and all work is GPLed.
It works great for reading stuff.
NB Don't forget to get Facebook App Key and set it in TestBB class.
But now I want to post something on my wall. So I've add new method to FacebookFacade class using Stream.publish API:
/***
* Publishes message to the stream.
* #param message - message that will appear on the facebook stream
* #param targetId - The ID of the user, Page, group, or event where
* you are publishing the content.
*/
public void streamPublish(String message, String targetId)
{
Hashtable arguments = new Hashtable();
arguments.put("method", "stream.publish");
arguments.put("message", message);
arguments.put("target_id", targetId);
try {
JSONObject result = new JSONObject(
int new JSONTokener(sendRequest(arguments)));
int errorCode = result.getInt("error_code");
if (errorCode != 0) System.out.println("Error Code: "+errorCode);
} catch (Exception e) {
System.out.println(e);
}
}
/***
* Publishes message on current user wall.
* #param message - message that will appear on the facebook stream
*/
public void postOnTheWall(String message)
{
String targetId = String.valueOf(getLoggedInUserId());
streamPublish(message, targetId);
}
This will return Error code 200, "The user hasn't authorized the application to perform this action"
First I thought it's related with Facebook -> Application Settings -> Additional Permissions -> Publish recent activity (one line stories) to my wall but even checked, no difference...
Then I've found this post explains that issue related with extended permissions.
This in turn should be fixed by modifying url a little in LoginScreen class :
public LoginScreen(FacebookFacade facebookFacade) {
this.facebookFacade = facebookFacade;
StringBuffer data = new StringBuffer();
data.append("api_key=" + facebookFacade.getApplicationKey());
data.append("&connect_display=popup");
data.append("&v=1.0");
//revomed
//data.append("&next=http://www.facebook.com/connect/login_success.html");
//added
data.append("&next=http://www.facebook.com/connect/prompt_permissions.php?" +
"api_key="+facebookFacade.getApplicationKey()+"&display=popup&v=1.0"+
"&next=http://www.facebook.com/connect/login_success.html?"+
"xxRESULTTOKENxx&fbconnect=true" +
"&ext_perm=read_stream,publish_stream,offline_access");
data.append("&cancel_url=http://www.facebook.com/connect/login_failure.html");
data.append("&fbconnect=true");
data.append("&return_session=true");
(new FetchThread("http://m.facebook.com/login.php?"
+ data.toString())).start();
}
Unfortunately it's not working. Still Error Code 200 in return to stream.publish request...
Do you have any suggestions how to resolve this?
Thank you!
I have posted the updated API on my website (http://www.baskoro.web.id/facebook-connect-blackberry-HOWTO.html) and this should solve this issue. Please let me know otherwise.
Salam. Cheers!
Eki