Get Facebook Pages Events using graph Api - android

I am trying to fetch facebook events from a pages profile using facebook graph api.
The method i was using is like below
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("https://graph.facebook.com/oauth/access_token?client_id="+APP_ID+"&client_secret="+APP_SECRET+"&grant_type=client_credentials");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String access_token = client.execute(get, responseHandler);
String uri = "https://graph.facebook.com/PageName/events?"+access_token.replace("|","%7C");
get = new HttpGet(uri);
String responseBody = client.execute(get, responseHandler);
in which APP_ID, APP_SECRET and PageName i am replacing with my details.
There is no issue as its working and i am getting the response also from Facebook as a json array which includes name,start_time,end_time,timezone,location,id of the events, but there is no event description.
How to fix this?

By default you don't get event description but you can add the same in using fields along with other information you require and retrieve more detailed listing. So you need to change your uri to
String uri = "https://graph.facebook.com/PageName/events?fields=name,start_time,timezone,location,description"+access_token.replace("|","%7C");
To retrieve the required information.

Use the Event ID you get in the response, and use it to get each and every detail of that event from:
"https://graph.facebook.com/EVENT_ID"

Related

Android - Google Sign-in on Web API - How to send Google Sign-in POST-request?

I've got an Android project that allows me to log-in with Google-accounts. Everything works as it's supposed to and I'm able to retrieve the Person's (com.google.android.gsm.model.people.Person) data, like Google email, username, profile picture url, etc.
I also have a Web API hosted online. In this Web API I can get a JSON-list of products by using the following: mywebhost/api/products.
Obviously these GET-requests are Authorized by OAuth 2.0, meaning I have to log-in with a Google Account on the mywebhost/Account/Login page to be authorized to get the JSON-list from the Web API. (When I'm not logged in, I receive the following JSON-list: {"$id":"1","Message":"Authorization has been denied for this request."})
I know how to send POST-requests in Android. For example with the code:
public class TaskPostAPI extends AsyncTask<String, Void, String>
{
GoogleApiClient googleAPI;
public TaskPostAPI(GoogleApiClient googleAPI){
this.googleAPI = googleAPI;
}
#Override
protected String doInBackground(String... urls){
String response = "";
for(String url : urls){
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
try{
List<NameValuePair> nvPairs = new ArrayList<NameValuePair>(3);
//nvPairs.add(new BasicNameValuePair("personName", Plus.PeopleApi.getCurrentPerson(googleAPI).getDisplayName()));
//nvPairs.add(new BasicNameValuePair("personGooglePlusProfile", Plus.PeopleApi.getCurrentPerson(googleAPI).getUrl()));
//nvPairs.add(new BasicNameValuePair("personEmail", Plus.AccountApi.getAccountName(googleAPI)));
// TODO: Use the correct nvPairs to be able to Log-in with the Google-account
post.setEntity(new UrlEncodedFormEntity(nvPairs));
HttpResponse execute = client.execute(post);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while((s = buffer.readLine()) != null)
response += s;
}
catch(Exception ex){
ex.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result){
// Do nothing yet
}
}
So, now the question:
In the code sample above, what should the nvPairs be to be able to successfully log-in with a Google-account. Or should I use something completely different than normal HttpPost to log-in with a Google-account on my Web API?
Also: The url provided is the default Log-in page. On this page I have three different options to log-in. Since we only want to use the Google log-in, how can I retrieve the url of the Google Log-in button from the Web API Login-page to use for the POST-request?
2b. With the second question: What Plug-in I could use in FireFox to see the links I'm redirected to? So I know which Login-url I should use instead of the default Login-page.
Thanks in advance for the responses.
Edit 1: I've tried a different approach, but I'm not sure it will work for the HttpGet-requests. What I've tried is opening a WebView with the Log-in page, and after I reach the page where I come when I successfully logged-in, I close the WebView.
However, when I use the HttpGet-requests, I still get the Unauthorized JSON back, so how can I use this WebView Log-in to make the HttpGet-request "believe" I'm logged-in and Authorized?
If someone still has an idea using the first approach (HttpPost-request), or if someone has a completely different approach, let me know.
Ok, I've found the POST I can use in the C# web project (/POST/ExternalLogin). There I also see what I should send:
In the header:
Content-Type application/x-www-form-urlencoded
Cookie with __RequestVerificationToken
In the body:
provider ("Google")
returnUrl
__RequestVerificationToken
The second __RequestVerificationToken needs to be a different one than the one used in the Cookie, but after decrypting it in the C# Web API it should be the same. This is the only problem I have right now, but I've got a different stackoverflow question for that.
For the full code:
public class TaskPostAPI extends AsyncTask<String, Void, String>
{
private String TOKEN = "__RequestVerificationToken";
#Override
protected String doInBackground(String... urls){
String response = "";
for(String url : urls){
HttpPost post = new HttpPost(url);
try{
// Add the default Content-type to the Header
post.addHeader("Content-type", "application/x-www-form-urlencoded");
// Get the baseUrl from the given url
URL u = new URL(url);
String baseUrl = u.getProtocol() + "://" + u.getHost();
// POST-request requires anti-forgery Cookie
// Get all Cookies
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie(baseUrl);
String[] cookies = cookie.split(";");
// Put all Cookies in a HashMap with cookieKey & cookieToken
HashMap<String, String> cookieStrings = new HashMap<String, String>();
for(String cook : cookies){
String[] cs = cook.split("=");
cookieStrings.put(cs[0], cs[1]);
}
// Add the Cookie to the Header
post.addHeader("Cookie", TOKEN + "=" + cookieStrings.get(TOKEN) + "");
// POST-request requires cookieToken, provider and returnUrl
List<NameValuePair> nvPairs = new ArrayList<NameValuePair>(3);
nvPairs.add(new BasicNameValuePair(TOKEN, cookieStrings.get(TOKEN)));
nvPairs.add(new BasicNameValuePair("provider", "Google"));
nvPairs.add(new BasicNameValuePair("returnUrl", baseUrl));
post.setEntity(new UrlEncodedFormEntity(nvPairs));
Log.i("COOKIE OUTPUT", TOKEN + "=" + cookieStrings.get(TOKEN) + "");
// Send the POST-request
HttpResponse execute = MainActivity.HttpClient.execute(post);
// Get the response of the POST-request
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while((s = buffer.readLine()) != null)
response += s;
}
catch(Exception ex){
ex.printStackTrace();
}
}
return response;
}
In this piece of code the following line is incorrect and still needs fixing:
nvPairs.add(new BasicNameValuePair(TOKEN, cookieStrings.get(TOKEN)));
cookieStrings.get(TOKEN) need to be replaced with the correct token to send.

How to send a POST request with JSON data using google api client library for java?

I'm trying to send a post request using the google api client library but not able to succeed.
This is the snippet I'm using
UrlEncodedContent urlEncodedContent = new UrlEncodedContent(paramMap); //paramMap contains email and password keypairs
HttpRequest request = httpRequestFactory.buildPostRequest(new GenericUrl(Constants.PHP_SERVICE_BASE_PATH + mPath) , urlEncodedContent);
String response = request.execute().parseAsString();
I do not get the expected response. I think it is because the post parameters i.e email and password are not being sent in the correct format. I need to send them in JSON.
NOTE : I'm not using the library for a google web service.
I'm using a Map as input of the JSON. The map is input for the JsonHttpContent used by the post request.
Map<String, String> json = new HashMap<String, String>();
json.put("lat", Double.toString(location.getLatitude()));
json.put("lng", Double.toString(location.getLongitude()));
final HttpContent content = new JsonHttpContent(new JacksonFactory(), json);
final HttpRequest request = getHttpRequestFactory().buildPostRequest(new GenericUrl(url), content);
UrlEncodedContent is used for posting HTTP form content (Content-Type: application/x-www-form-urlencoded). If the Content-Type is application/json you should probably use
http://code.google.com/p/google-http-java-client/source/browse/google-http-client/src/main/java/com/google/api/client/http/json/JsonHttpContent.java

In-app Twitter timeline without authentication?

Lately, I have been working on an app to see if I could do some stuff like a Twitter timeline correctly.
I created a nice little ListView, let some options link to a site, let one option call a Dialog to choose a Twitter account, and accomplished a Twitter feed viewer.
However, it doesn't seem to be possible to actually retrieve a user's timeline without authentication with Twitter? Or is it possible? If so, how do I do that?
Can I retrieve and display a user's Twitter feed without authentication, and how?
Yes, you can either use the twitter search API, which returns json formatted data, which you must parse, just search the documentation. Alternatively, you can use a direct link to a user's timeline like so:
https://twitter.com/statuses/user_timeline/user.json
EDIT: This returns the response as .json for me, next it needs to be parsed. Make sure you are parsing the response AFTER it has been received, it looks like you are starting the request and then jumping to parsing it, before the request is complete.
public ArrayList<Tweet> getTweets(String Account, int page) {
String accountUrl = "http://search.twitter.com/search.json?q=#"
+ Account + "&rpp=100&page=" + page;
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(accountUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try{
responseBody = client.execute(get, responseHandler);
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
// parse response, return arraylist
}catch(Exception ex) {
ex.printStackTrace();
}
}

how to pass parameters to RESTlet webservice from android?

I've been looking online for how to pass parameters to RESTlet webservice but it seem there are not much tutorial concerning RESTlet.
I would like to send some parameters gathered from a form on my android application (it would be great if i could do this using JSON).
well i solved this
as for the server side
#Post
public JSONArray serverSideFunction(Representation entity)
throws JSONException {
try {
JSONObject req = (new JsonRepresentation(entity)).getJsonObject();
System.out.println(req.getString(/* filed name */));
System.out.println(req.getString(/* filed name */));
/*
* you can retrieve all the fields here
* and make all necessary actions
*/
} catch (IOException e) {
e.printStackTrace();
}
}
as for the Android Side
HttpClient client = new DefaultHttpClient();
String responseBody;
JSONObject jsonObject = new JSONObject();
try{
HttpPost post = new HttpPost(WebService_URL);
jsonObject.put("field1", ".........");
jsonObject.put("field2", ".........");
StringEntity se = new StringEntity(jsonObject.toString());
post.setEntity(se);
post.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setHeader("Content-type", "application/json");
Log.e("webservice request","executing");
ResponseHandler responseHandler = new BasicResponseHandler();
responseBody = client.execute(post, responseHandler);
/*
* You can work here on your responseBody
* if it's a simple String or XML/JSON response
*/
}
catch (Exception e) {
e.printStackTrace();
}
I hope this may be of help
In fact, it depends on what you want to do. With REST (see http://en.wikipedia.org/wiki/Representational_state_transfer), there are two ways to pass parameters or data. Before you need to understand some concepts:
Resource: the REST entity by itself.
Representation: corresponds to its state and can be gotten or updated using different HTTP methods. The kind of content is identified using the content type header (media type in Restlet).
Methods: the GET method is used to get the resource state, PUT to update it, POST to create a new resource and specify its state the same time, DELETE to delete a resource.
Restlet provides Java entities for REST elements.
So, after described that, you can see that passing data or parameters depends of your use case:
1°) Do you want to update the resource state? In this case, you will use the content of the request with methods like POST or PUT. The data structure is free from text, JSON, XML or binary... Restlet provides the ClientResource class to execute requests on RESTful applications. It also provides support to build the representation to send and extract data from the one received. In this case, your data gathered from a form will be used to build the representation. Here are some samples:
//Samples for POST / PUT
ClientResource cr = new ClientResource("http://...");
cr.post(new StringRepresentation("test"));
MyBean bean = new MyBean();
(...)
//Jackson is a tool for JSON format
JacksonRepresentation<MyBean> repr
= new JacksonRepresentation<MyBean>(bean);
cr.put(repr);
//Samples for GET
Representation repr1 = cr.get();
bean = (new JacksonRepresentation<MyBean>(repr1, MyBean.class)).getObject();
2°) Do you want to specify parameters on your GET requests (for example to configure data to retreive and so on)? In this case, you can simply add it on the ClientResource, as described below:
ClientResource cr = new ClientResource("http://...");
cr.getReference().addQueryParameter("q", "restlet");
Representation repr = cr.get();
In this case, your data gathered from a form will be used to build the parameters.
Hope it helps you.
Thierry
If you want request with json structure and your response as JSONObject maybe you can do like this in server side:
public class RequestJSON extends ServerRecource{
#Post("json")
public JSONObject testRequest(String entity){
JSONObject request = new JSONObject(entity);
String value1 = request.getString("key1");
int value2 = request.getInt("key2");
return /* your JSONObject response */;
}
}
And your request can be :
{"key1":"value1", "key2":value2}
I hope this can help you

Android: Unable to login to a web session and parse XML data using DOM on the same login session

Android Development: I'm needing to log into a web session using POST, then make another request of which I parse XML to get Lat/Long, then submit this to a google maps overlay.
My issue is I'm able to log into my system, but when I submit a command to parse XML, it is acting like a completely new session and I basically get an 'incorrect login' reply from the server.
Does anyone have some simple steps to perform this...and to keep a session open for as many commands as I need? I'm not actually SURE I'm using a session cookie, but believe this is the case.
Some example code may be:
try {
URI loginUri = new URI("http://www.mywebsite.com/ExternalLogin.jsp?user=lee&pwd=bluedog");
URI xmlUri = new URI("http://www.mywebsite.com/getXMLInfo.xml");
// Prepares the request.
HttpClient httpClient = new DefaultHttpClient();
HttpGet loginHttpGet = new HttpGet();
loginHttpGet.setURI(loginUri);
HttpGet xmlHttpGet = new HttpGet();
xmlHttpGet.setURI(xmlUri);
// Sends the request and read the response
HttpResponse loginResponse = httpClient.execute(loginHttpGet);
InputStream loginInputStream = loginResponse.getEntity().getContent();
HttpResponse xmlResponse = httpClient.execute(xmlHttpGet);
InputStream xmlInputStream = xmlResponse.getEntity().getContent();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(xmlInputStream.toString()));
doc.getDocumentElement();
// Continue using DOM to parse my XML data
}
You don't indicate your how our "web session" is being maintained. I am going to guess it is via a session cookie. If so, use HttpClient and keep using the same HttpClient object for both requests. The session cookies will be handled automatically.

Categories

Resources