I searched lot and I can see some questions same as mine in StackOverflow too but didn't get answer.
I need to get user(google+ and facebook) messages whatever posted by him under his/her account and give it as xml response to a mobile app which is going to show user posts as better format/design - so here I need to fetch the posts from google+/facebook using the profile-id/username.
Eg: Like from twitter I can able to see status from
https://api.twitter.com/1/statuses/user_timeline.xml?include_entities=true&include_rts=true&screen_name=screenname&count=2
Is there any library or any particular way by which i can get it?
Thanks in Advance.
I can only speak to Facebook and Twitter, as they are the only two Social Media API's I have utilized.
Both API's are RESTful services. For Twitter and Facebook, you will need to create applications on the perspective platforms in order to obtain an OAuth token for your applications that will be fetching the data via the RESTful services.
For FaceBook, you can utilize the Graph API explorer for development. This enables you to develope without creating an application on the FaceBook platform.
Both FaceBook and Twitter have community driven projects for accessing these web services in various languages. Since you are doing this for the Android, I assume you would like your program for fetching this data in Java.
RestFB is my recommendation for a Java FaceBook library
FacebookClient facebookClient = new DefaultFacebookClient(authToken);
User facebookUser = facebookClient.fetchObject("me", User.class);
Twitter4j is a great Java Twitter library
For FaceBook, core concepts is a great place to start.
For more information on Twitter on see the overview documentation
You can use the activities API for Google+. This is currently restricted to public posts but should be enough to get you started. The profile ID comes from a user's profile. There are other ways you can get this content as well, including the search API.
The documentation and simple examples from various languages can be found on the Google plus page (https://developers.google.com/+/api/latest/activities) and the following JavaScript example could be helpful for justing seeing how things work:
// globals used for auth, showing debugging
var debug = true;
var key = "your api key from https://code.google.com/apis/console";
function handleRequestIssue(request){
// For now, just show the error
console.log("Error, status:" + request.status + " / response:" + request.responseText);
}
function performXHR(URL){
var objReturn = "";
var request = new XMLHttpRequest();
request.open('GET', URL, false);
request.send(); // because of "false" above, will block until the request is done
// and status is available. Not recommended, however it works for simple cases.
if (request.status === 200) {
if (debug) console.log(request.responseText);
var objReturn = jQuery.parseJSON(request.responseText).items;
if (debug){
for (value in objReturn){
console.log(value);
}
}
}else{
handleRequestIssue(request);
}
return objReturn;
}
// Gets the activities for a profile
function getActivities(profileID){
var activities = null;
var URL = "https://www.googleapis.com/plus/v1/people/" + profileID + "/activities/public?alt=json&key=" + key;
activities = performXHR(URL);
console.log(activities.length);
return activities;
}
You can at this point see the activities in your debugger. You could always render the content as HTML inside a div or something.
function renderActsComments(activities, identifier, filter){
var renderMe = "";
console.log("activities retrieved: " + activities.length);
for (var i=0; i < activities.length; i++) {
var render = true;
console.log("trying to do something with an activity: " + i);
var activity = activities[i];
if (filter != null && filter.length > 0){
if (activity.crosspostSource.indexOf(filter) == -1){
render = false;
}
}
if (render == true){
renderMe += "<br/><div class=\"article\"><p>" + activity.title + "</p>";
console.log(activity.id);
// get comments
var comments = getCommentsForActivity(activity.id);
var left = true;
for (var j=0; j<comments.length; j++){
if (left){
left = false;
renderMe += "<br/><p class=\"speech\">" + comments[j].object.content + "</p>";
renderMe += "" + comments[j].actor.displayName + "";
renderMe += "<a href=\"" + comments[j].actor.image.url.replace(/\?.*/, "") + "\">";
renderMe += " <img border=0 src=\"" + comments[j].actor.image.url + "\"/></a>";
renderMe += "</p>";
}else{
renderMe += "<br/><p class=\"speechAlt\">" + comments[j].object.content + "</p>";
left = true;
renderMe += "<p class=\"profileAlt\">";
renderMe += "<a href=\"" + comments[j].actor.image.url.replace(/\?.*/, "") + "\">";
renderMe += "<img border=0 src=\"" + comments[j].actor.image.url + "\"/></a>";
renderMe += " " + comments[j].actor.displayName + "";
renderMe += "</p>";
}
}
renderMe += "</div>";
}
}
console.log("I'm done");
document.getElementById(identifier).innerHTML = renderMe;
return renderMe;
}
Related
I am developing an Android app in Unity. I am trying to make UnityWebRequests to work with Vuforia's Web Services API. Currently every method works - GET/PUT/DELETE, but I cannot POST anything, I always get an error:
Error:Generic/unknown HTTP error
Response code:400
Even though according to Vuforia's documentation POST requires the same request body as PUT and I am generating it using the same approach:
public string CreateNewUpdateBody(Text name, Text width, RawImage image, Toggle active_flag, Text application_metadata)
{
dynamic BodyData = new System.Dynamic.ExpandoObject();
if (!string.IsNullOrEmpty(name.text))
{
BodyData.name = name.text; // mandatory for post
}
if (!string.IsNullOrEmpty(width.text))
{
BodyData.width = float.Parse(width.text); // mandatory for post
}
if (image.texture != null)
{
Texture2D texture = (Texture2D)image.texture;
BodyData.image = System.Convert.ToBase64String(ImageConversion.EncodeToJPG(texture)); // mandatory for post
}
if (active_flag.interactable)
{
BodyData.active_flag = active_flag.isOn;
}
if (!string.IsNullOrEmpty(application_metadata.text))
{
BodyData.application_metadata = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(application_metadata.text));
}
string json = JsonConvert.SerializeObject(BodyData);
Debug.Log("Body data: " + json);
return json;
}
Then I send the web request like this:
private IEnumerator PostTarget(MonoBehaviour mono, string postBody)
{
var request = UnityWebRequest.Post(url + "/targets", postBody);
SetHeaders(request); // Must be done after setting the body
Debug.Log("Starting request " + request.method + " " + request.url);
yield return request.SendWebRequest();
while (!request.isDone) yield return null;
if (request.isHttpError || request.isNetworkError)
{
Debug.LogError("Request was not completed");
Debug.LogError("Error:" + request.error + " Response code:" + request.responseCode);
Debug.LogError(request.downloadHandler.text); // result_code is always just "Fail"
mono.StopAllCoroutines();
yield break;
}
else
{
Debug.Log("Request completed successfuly!");
Debug.Log(request.downloadHandler.text);
}
response = JsonUtility.FromJson<ResponsePostNewTarget>(request.downloadHandler.text);
Debug.Log("\nCreated target with id: " + response.target_id);
}
Any thoughts or suggestions? I appreciate the time you take to read this.
If everything works BUT posting data, either 1 vuforia doesn't support it or 2 (most likely) you're missing something.
Try adding this to your request
private UploadHandler GetUploadHandler(string postBody)
{
UploadHandler handler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(postBody));
handler.contentType = "application/json";
return handler;
}
And call it after SetHeaders
request.uploadHandler = GetUploadHandler(postBody);
I'm looking now in Bloomberg Data License Web Services. Note, that this is different from Bloomberg API ( Session/Service/Request, b-pipe, etc ). It is SOAP-based solution to retrieve reference data from Bloomberg DBs. I created a test application just to quickly evaluate this solution:
var client = new PerSecurityWSClient("PerSecurityWSPort");
client.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2("{path-to-certificate}", "{password}");
client.ClientCredentials.UserName.UserName = "";
client.ClientCredentials.UserName.Password = "";
client.ClientCredentials.Windows.ClientCredential.Domain = "";
var companyFields = new string[] { "ID_BB_COMPANY", "ID_BB_ULTIMATE_PARENT_CO_NAME" , /* ... all other fields I'm interested in */ };
var getCompanyRequest = new SubmitGetCompanyRequest {
headers = new GetCompanyHeaders { creditrisk = true },
instruments = new Instruments {
instrument = new Instrument[] {
new Instrument { id = "AAPL US", yellowkey = MarketSector.Equity, yellowkeySpecified = true },
new Instrument { id = "PRVT US", yellowkey = MarketSector.Equity, yellowkeySpecified = true }
}
},
fields = companyFields
};
var response = client.submitGetCompanyRequest(getCompanyRequest);
if(response.statusCode.code != SUCCESS) {
System.Console.Error.WriteLine("Response status is " + response.statusCode);
return;
}
var retrieve = new RetrieveGetCompanyRequest { responseId = response.responseId };
RetrieveGetCompanyResponse getCompanyResponse = null;
do {
System.Console.Write("*");
Thread.Sleep(1000);
getCompanyResponse = client.retrieveGetCompanyResponse(retrieve);
} while (getCompanyResponse.statusCode.code == DATA_NOT_AVAILABLE);
if (getCompanyResponse.statusCode.code != SUCCESS) {
System.Console.Error.WriteLine("Response status is " + response.statusCode);
return;
}
System.Console.WriteLine();
foreach (var instrumentData in getCompanyResponse.instrumentDatas) {
Console.WriteLine("Data for: " + instrumentData.instrument.id + " [" + instrumentData.instrument.yellowkey + "]");
int fieldIndex = 0;
foreach (var dataEntry in instrumentData.data) {
if (dataEntry.isArray) {
Console.WriteLine(companyFields[fieldIndex] + ":");
foreach(var arrayEntry in dataEntry.bulkarray) {
foreach(var arrayEntryData in arrayEntry.data) {
Console.WriteLine("\t" + arrayEntryData.value);
}
}
}
else {
Console.WriteLine(companyFields[fieldIndex] + ": " + dataEntry.value);
}
++fieldIndex;
}
System.Console.WriteLine("-- -- -- -- -- -- -- -- -- -- -- -- --");
}
The code looks somewhat bloated (well, it is indeed, SOAP-based in 2015). Hence is my question -- I assume there should be some wrappers, helpers, anything else to facilitate reference data retrieval, but even on SO there is only one question regarding BB DLWS. Is here anyone using DLWS? Are there any known libraries around BB DLWS? Is it supposed to be that slow?
Thanks.
I'm just getting into this myself. There are two options for requesting data: SFTP and Web Services. To my understanding, the SFTP option requires a Bloomberg application ("Request Builder") in order to retrieve data.
The second option (Web Services) doesn't seem well-documented, at least for those working with R (like myself). So, I doubt a library exists for Web Services at this point. Bloomberg provides an authentication certificate in order to gain access to their network, as well as their web services host and port information. Now, in terms of using this information to connect and download data, that is still beyond me.
If you or anyone else has been able to successfully connect and extract data using Bloomberg Web Services and R, please post the detailed code to this Blog!
I'm struggling to get other user's mention timeline with twitter4j api. I could figure out that it's possible only to get other user's UserTimeline. It seems that there is no way to get other user's mention timeline
(I found that here - lookup "Interface TimelinesResources")
Is there way to get other user's mention timeline ???
You can get the MentionsTimeline using getMentionsTimeline() method of TimelineResources as a link you mentioned with some limitations of number of tweets returned.
Find below example of the example which will give you MentionsTimeline.
Twitter twitter = new TwitterFactory().getInstance();
try {
User user = twitter.verifyCredentials();
List<Status> statuses = twitter.getMentionsTimeline();
System.out.println("Showing #" + user.getScreenName() + "'s mentions.");
for (Status status : statuses) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get timeline: " + te.getMessage());
System.exit(-1);
}
You can use getUserTimeline() method of Twitter class.
References:
1. http://twitter4j.org/javadoc/twitter4j/Twitter.html
2. http://twitter4j.org/javadoc/twitter4j/Status.html
The Twitter API doesn't have an endpoint for viewing other users mentions (the statuses/mentions_timeline API returns only the mentions of the authenticated user).
You should use the search API, using as the query string the #screen_name of the user you want to get the mentions. Please note that the Twitter Search API may not return all mentions for a given user (it says that "the Search API is focused on relevance and not completeness").
So, using Twitter4j, you can get #NASA mentions using the following
Twitter twitter = new TwitterFactory().getInstance();
try {
Query query = new Query("#NASA");
QueryResult result;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("#" + tweet.getUser().getScreenName() + " - " + tweet.getText());
}
} while ((query = result.nextQuery()) != null);
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
}
I am retrieving the complete list of a friend's likes(the list of pages that the user likes) using the code bellow:
Uri ex_a = new System.Uri("https://graph.facebook.com/" + friend_id + "/likes? access_token=" + token);
WebClient WC_a = new WebClient();
WC_a.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(list_likes);
WC_a.DownloadStringAsync(ex_a);
private void list_likes(object ob, DownloadStringCompletedEventArgs e)
{
JsonObject jo = new JsonObject(e.Result);
JsonArray dataArray = (JsonArray)jo["data"];
if (dataArray.ToString().Length > 2)
{
foreach (JsonObject account in dataArray)
{
list_of_likes.Add(new class_of_likes("http://graph.facebook.com/" + (string)account["id"] + "/picture?type=small", (string)account["name"]));
}
}
}
However, in October 2013, this approach will only retrieve 25 results/request.
I need to know how to create a loop to get the remaining results because facebook uses pagination like:
"paging": {
"next": "https://graph.facebook.com/user_id/likes?limit=25&offset=25&__after_id=last_page_id"
Thank you.
Get pagination section, and parse it to get next_page value, then send a query for it. There's no automatic process or get all method , otherwise spams/bots would be the happiest creature in this world.
I am newbie for such kind of social networking Application integration using blackberry API.
i want to develope such kind of application which can use the facebook or twitter social networking site integration using available blackberry api.
how to access the faceBook using blackberry API?
Is there any webservice available of facebook on which blackberry api can work and access it?
is there any application exist with whole source code for accessing the facebook using the blackberry api?
if anybody has any solution or any useful link or any code snippet,which would be appreciated.:)
Thanks,
Mishal
Facebook offers a webservice-based API that you can use - they provide information about it here:
http://wiki.developers.facebook.com/index.php/Platform_Basics
I would strongly recommend using the Sun Java Wireless Toolkit (Sun Java Wireless Toolkit 2.5.2_01 for CLDC available here: SJW Toolkit) - use the Utilities application when installed and then the "Stub Generator" - it will create J2ME classes and stubs for all web service calls that you can then bring into your BlackBerry project. I have used this without fail to call web services from the BlackBerry and it is much easier than creating your own web service call wrappers. Everything will be strong typed and any required objects and classes will all be created for you.
BlackBerry FaceBook Connect
See code sample provided by Eki Y. Baskoro: Facebook Connect on Blackberry
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.
BlackBerry Twitter Connect
And talking about twitter, there is a twitter api and opensource j2me client - jibjib to look at.
Sample to post status:
class Scr extends MainScreen implements FieldChangeListener {
BasicEditField musername;
BasicEditField mPassword;
BasicEditField mStatus;
ButtonField mUpdateStatus;
public Scr() {
add(musername = new BasicEditField("username: ", ""));
add(mPassword = new BasicEditField("password: ", ""));
add(mStatus = new BasicEditField("status: ", ""));
mUpdateStatus = new ButtonField(ButtonField.CONSUME_CLICK);
mUpdateStatus.setLabel("update status");
mUpdateStatus.setChangeListener(this);
add(mUpdateStatus);
}
public void fieldChanged(Field field, int context) {
if (mUpdateStatus == field) {
String username = musername.getText().trim();
String password = mPassword.getText().trim();
String status = mStatus.getText().trim();
updateStatus(username, password, status);
} else {
}
}
void updateStatus(String username, String password, String status) {
String response = "";
try {
String query = "status=" + urlEncode(status);
String len = String.valueOf(query.length());
SocketConnection hc = (SocketConnection) Connector
.open("socket://twitter.com:80");
DataOutputStream dout =
new DataOutputStream(hc.openOutputStream());
DataInputStream din = new DataInputStream(hc.openInputStream());
String userPass = username + ":" + password;
byte[] encoded = Base64OutputStream.encode(userPass.getBytes(), 0,
userPass.length(), false, false);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String request = "POST /statuses/update.json HTTP/1.1\r\n"
+ "Host: twitter.com:80\r\n"
+ "User-Agent: curl/7.18.0 (i486-pc-linux-gnu) " +
"libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 " +
"libidn/1.1\r\n"
+ "Accept: */*\r\n"
+ "Content-Type: application/x-www-form-urlencoded\r\n"
+ "Content-Length: " + len + "\r\nAuthorization: Basic "
+ new String(encoded) + "\r\n\r\n";
bos.write(request.getBytes());
bos.write(query.getBytes());
dout.write(bos.toByteArray());
dout.flush();
dout.close();
byte[] bs = new byte[900];
din.readFully(bs);
bos = new ByteArrayOutputStream();
bos.write(bs);
din.close();
hc.close();
response = bos.toString();
} catch (Exception ex) {
System.out.println(ex.getMessage()+" "+response);
}
}
public static String urlEncode(String s) {
if (s != null) {
try {
s = new String(s.getBytes("UTF-8"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
}
StringBuffer tmp = new StringBuffer();
try {
for (int i = 0; i < s.length(); i++) {
int b = (int) s.charAt(i);
if ((b >= 0x30 && b <= 0x39) || (b >= 0x41 && b <= 0x5A)
|| (b >= 0x61 && b <= 0x7A)) {
tmp.append((char) b);
} else if (b == 0x20) {
tmp.append("+");
} else {
tmp.append("%");
if (b <= 0xf) {
tmp.append("0");
}
tmp.append(Integer.toHexString(b));
}
}
} catch (Exception e) {
}
return tmp.toString();
}
return null;
}
}
UPDATE
Twitter API ME lib v.1.8 for RIM is available on Project Kenai
Twitter Basic Auth method is deprecated starting today.
You must now use OAuth ...
for connecting to Facebook from blackberry using native apps you can use Facebook sdk for blackberry. you can download from github.com. search for Facebook sdk. it will also comes with some samples which clearly demonstrates the usage of Facebook api.