Android: Facebook Applink cURL to java - android

I have been trying to get the cURL command translated into java code so that I can create a new AppLink object: https://developers.facebook.com/docs/applinks/hosting-api
I downloaded cURL and then typed in the following in Windows which worked and returned a applink ID:
curl -k -g https://graph.facebook.com/app/app_link_hosts -F
access_token="INSERTED MY OWN APP_TOKEN" -F name="Android App Link
Object Example" -F
android='[{"url":"sharesample://story/1234","package":"com.facebook.samples.sharesample","app_name":"ShareSample",},]'
-F web='{"should_fallback" : false,}'
Would anyone know how to convert the curl code into Java so that I can use it on my server?
Also I would like to find out if there is a way to found to query for all the applinks that are created for a particularly package name so that I can see everything that was created?
Thanks!

I spent hours researching this and finally found this piece of code from 1997 that I thought might no longer work as methods get deprecated and modified it for facebook applinks: http://www.javaworld.com/article/2077532/learn-java/java-tip-34--posting-via-java.html
Then I used Spring to generate this endpoint and now its working and returns an app link id:
#RequestMapping(value="/applink", method=RequestMethod.GET)
public void applink() {
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
try {
url = new URL ("https://graph.facebook.com/app/app_link_hosts");
// URL connection channel.
urlConn = url.openConnection();
// Let the run-time system (RTS) know that we want input.
urlConn.setDoInput (true);
// Let the RTS know that we want to do output.
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
// Specify the content type.
urlConn.setRequestProperty
("Content-Type", "application/x-www-form-urlencoded");
// Send POST output.
printout = new DataOutputStream (urlConn.getOutputStream ());
String content =
"access_token=" + URLEncoder.encode("INSERT APP ACCESS TOKEN", "UTF-8") +
"&name=" + URLEncoder.encode("Android App Link Object Example", "UTF-8") +
"&android=" + URLEncoder.encode("[{'url':'sharesample://story/1234', 'package':'com.facebook.samples.sharesample','app_name':'ShareSample'}]", "UTF-8") +
"&web=" + URLEncoder.encode("{'should_fallback' : false}", "UTF-8");
printout.writeBytes(content);
printout.flush ();
printout.close ();
// Get response data.
input = new DataInputStream (urlConn.getInputStream ());
BufferedReader d = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String str;
while (null != ((str = d.readLine())))
{
System.out.println (str);
//textArea.appendText (str + "\n");
}
input.close ();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

HTTPURLConnection - Outputstream POST to php on webserver

I'm getting mad about HttpUrlConnection an Outputstreams.
I just want to send a string to php and from there put it in a database.
The last two nights I read nearly thousand guides and threads about sending data to webserver, tried almost everything I read - and it's still not working.
protected void phpPOST(final String ServerURL, final String StringToPost)
{
Thread newthread = new Thread() {
public void run() {
//1. set URL and connect to server
HttpURLConnection connection = null;
try {
URL server = new URL(ServerURL + "teilnehmer_update.php");
connection = (HttpURLConnection) server.openConnection();
//2. set method to POST and enable output
connection.setRequestMethod("POST");
connection.setDoOutput(true);
//3. open outputstream and send string to url
OutputStreamWriter outstream = new OutputStreamWriter(connection.getOutputStream());
outstream.write(StringToPost);
outstream.flush();
outstream.close();
} catch (Exception e) {
e.printStackTrace();
Log.i("Error!", "ERROR is " + e);}
finally {if (connection != null) {connection.disconnect();}}
}
};
newthread.start();
}
I reduced my php-file to very simple, to secure it's not a php problem. Tried from browser, works fine.
<?php
// for testing, should create an empty file when no no data is recieved.
$file = fopen('test.txt', 'w');
$id = $_POST['id'];
fwrite($file, $id);
fclose($file);
?>
I don't get any errors - so, I don't know what to fix. LogCat is also empty.
I think the Problem is something with the Outputstream (also tried versions BufferdOS,OS,DataOS). As far as I get it, the connection is should open when I create the OS and write to it. - But, in my case it does not do anything...
Any ideas what's wrong with the code ?
Thanks

Android: extracting website using BufferedReader: Information extracted are outdated

I am reading html source code of a public website using the following code:
Code:
#Override
protected Void doInBackground(Void... params)
{
try
{
URL url = new URL(""+URL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
PageCode = "";
OriginalPageCode = "";
while ((inputLine = in.readLine()) != null)
{
PageCode += inputLine;
}
OriginalPageCode = PageCode;
try
{
extract_website_and_save(); // extracting data from PageCode
}
catch (Exception e1)
{
}
in.close();
}
Background:
The above code sometimes can fetch the most updated website properly. But occasionally it linked to an outdated version of the website and hence unable to obtain the most updated information for the website.
I am curious why the above will occur, does it related to extracting from cache instead of the real updated website??
I therefore used Chrome to browse the same link, and discovered that Chrome also fetched the outdated website.
I have tried restarting the device, but the problem continues.
After 30 minutes to an hour, I requested the app to fetch again and it then can extract the most updated information. I at the same time browse the website using Chrome, Chrome can now obtain the most updated website.
Question:
The above BufferedReader should have no relationship with Chrome? But they follow the same logic and hence extracting from cache instead of from the most updated website?
I strongly suspect the end point is being cached by URL
Try something like this
urlSrt = urlSrt + "?x=" + new Random().nextInt(100000);
// If your URL already is passing parameters i.e. example.com?x=1&p=pass - then modify
// the urlSrt line to to use an "&" and not "?"
// i.e. urlSrt = urlSrt + "&x=" + new Random().nextInt(100000);
URL url = new URL(urlSrt);
URLConnection con = url.openConnection();
con.setUseCaches(false); //This will stop caching!
So if you modify your code to something like this.
URLConnection con = url.openConnection();
con.setUseCaches(false);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));

Downloading and parsing JSON on Android

I just want to ask what is the proper way of converting this into android code using HTTP get..
Basically I need to login to the website and do some specific search...
This is the actual code I have a problem with:
curl -H "Content-type: application/json" --basic --user "username:passowrd" -X GET -G \
--data-urlencode "status=triggered" \
--data-urlencode "assigned_to_user="\
"https://yourdomain.pagerduty.com/api/v1/incidents"
I am not sure if I can do that using put..
Example:
object.put("--data-urlencode", status=triggered)
and also for the username and password I am not sure if I can also do something like this
object.put("username", "romel");
object.put("password", "passwd");
If you are having HTTP Basic Auth problems, try this code to set your username and password...
HttpURLConnection con;
String basicAuthUsername = "username";
String basicAuthPassword = "passowrd"; //do you have a typo here??
try {
URL url = new URL(urlString);
con = (HttpURLConnection)url.openConnection();
if (basicAuthUsername != null && basicAuthPassword != null) {
String userAndPass = new StringBuilder(basicAuthUsername).append(":").append(basicAuthPassword).toString();
con.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(userAndPass.getBytes(), Base64.NO_WRAP));
}
//con.setRequestMethod("POST");
con.setRequestMethod("GET");
con.setUseCaches(false);
int responseCode = con.getResponseCode();
//etc...
}
finally {
//close con, etc.
}
...also, maybe you have mistyped your password??
Your question isn't too detailed so I'm entirely sure what you're looking for - is it an authentication problem or JSON in general?
Handling JSON in Android is pretty well covered in a few places, including Vogella's tutorial.
Writing JSON is pretty easy, as in Vogella's example:
public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "Jack Hack");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Hacker");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);
}
Headers for things like content type are easy to add on your HTTPGet object as well, for example:
HttpGet httpGet = new HttpGet(API_URL);
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Content-type", "application/json");
These are only snippets, use the tutorial linked above for a better, fuller explanation. Hope this helps.

Creating a playlist with Youtube DATA API on Android

I am trying to use the Youtube GDATA API in order to add a new playlist to a youtube account.
I base my code on the documentation: https://developers.google.com/youtube/2.0/developers_guide_protocol_playlists#Adding_a_playlist
I first get an access token and use my developer key appropriately.
The post seems to work just fine, but when trying to get back the response, I get a file not found exception while calling getInputStream.
Does anyone has an idea?
Thanks
Here is the connection code (an updated cleaner version):
#Override
protected Boolean doInBackground(Void... arg0) {
BufferedReader input = null;
InputStreamReader inputStreamReader = null;
StringBuilder postContentXml = new StringBuilder();
postContentXml.append("<?xml version='1.0' encoding='UTF-8'?>").
append("<entry xmlns='http://www.w3.org/2005/Atom'") .
append(" xmlns:yt='http://gdata.youtube.com/schemas/2007'>").
append("<title type='text'>Sports Highlights Playlist</title>").
append("<summary>A selection of sports highlights</summary>").
append("</entry>");
byte[] buffer = postContentXml.toString().getBytes();
StringBuilder response = new StringBuilder();
try {
URL url = new URL("https://gdata.youtube.com/feeds/api/users/default/playlists");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Initialize connection parameters
urlConnection.setConnectTimeout(30000);
urlConnection.setReadTimeout(30000);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
// Headers initialization
urlConnection.setRequestProperty("Content-Type", "application/atom+xml");
urlConnection.setRequestProperty("Content-Length", String.valueOf(buffer.length));
urlConnection.setRequestProperty("Authorization", mAuthToken);
urlConnection.setRequestProperty("GData-Version", "2");
urlConnection.setRequestProperty("X-GData-Key", YoutubeUtils.getDevKey());
OutputStream os = urlConnection.getOutputStream();
os.write(buffer, 0, buffer.length);
os.flush();
os.close();
InputStream inputStream = urlConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
input = new BufferedReader(inputStreamReader, 4096);
String strLine = null;
while ((strLine = input.readLine()) != null) {
response.append(strLine);
}
input.close();
inputStreamReader.close();
inputStream.close();
urlConnection.disconnect();
Log.d("CreatePlaylistTask", "Response: " + response);
}
catch(Exception e) {
Log.d("CreatePlaylistTask", "Error occured: " + e.getMessage());
}
return true;
}
I'm assuming that the POST wasn't actually successful.
If I had to guess from looking at your code, I'd think that the problem might be the Authorization header value. What does myAuthToken look like, and what type of token is it? If it's an OAuth 2 token, for instance, then the value needs to be Bearer TOKEN_VALUE, not just TOKEN_VALUE.
Also, please note that v3 of the YouTube Data API will be released in the near future, and it will offer better support on Android using the new Google APIs Client Library for Java.
I have put together a sample Android application which uses the YouTube Data v3 API to demonstrate how you can load a playlist into a ListView.
https://github.com/akoscz/YouTubePlaylist
Note that you MUST have a valid API key for this sample application to work. You can register your application with the Google Developer Console and enable the YouTube Data API. You need to Register a Web Application NOT an Android application, because the API key that this sample app uses is the "Browser Key".

Want to post data from an Android app to rails web-app which uses Devise for authentication

I have an existing Rails app which uses Devise to handle authentication. The app works fine in the browser.
I want a user on the phone to be able to sign into the app and post data into a form. This requires the authentication_token, however when I sign-in with JSON the response does not include this.
What setting do I need to change in initialisers/devise.rb to get the authentication token?
Antony
I dont really know how to get the cookies from a json request eigther.
I have done something similar a while back but with yaml.
This is what i did to get the token. (i replaced text/yaml by application/json. again donno if it works, but it might be worth a shot.
try {
data = "--- \nusername: " + name + "\n" + "password: " + password;
URL myserver = new URL(server + "wannabe");
URLConnection con = myserver.openConnection();
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "*, */*");
con.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(data);
out.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(
con.getInputStream()));
String decode;
while ((decode = in.readLine()) != null){
output += decode;
}
out.close();
in.close();
} catch(IOException e){
throw new TokenException("Wrong Username/password");
}
//Stripping begin and end quotes
return output.substring(1, output.length() -1);

Categories

Resources