Reading a DropBox Text File - android

I have an android app that loads images and text files into Dropbox. I've figured out the authentication and upload process.
Now, using the same authenticated session, I want to read one of the uploaded text files (to look for changes). I've found a download example, but that would mean writing it to local SD, then reading for there ... not efficient at all (in part because of the additional android permission required).
I've examined Dropbox's v2 documentation and there do seem to be a bunch of read calls but I can't, for the life of me, figure out how to use them. The helpful Android-Dropbox examples also don't seem to tackle my specific problem. I couldn't find any v2 examples on stackoverflow either.
Surely, somebody can point me to a simple example that provides a nice InputStream.

You can use the Dropbox Java SDK download method to get file contents directly. There's an example of using that in the example app here. That example writes directly to a FileOutputStream.
It sounds like you just want an InputStream though, which would look like this:
DbxClientV2 client = new DbxClientV2(config, ACCESS_TOKEN);
String remotePath = "/test.txt"; // the path to the file you want to download
InputStream fileInputStream = null;
try {
fileInputStream = client.files().download(remotePath).getInputStream();
// use `fileInputStream` as desired
} catch (DbxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

After much tooling around, here's something that works
String my_link = null;
URL my_url = null;
URLConnection conn = null;
BufferedReader reader = null;
try {
my_link = my_DbxClient.files().getTemporaryLink("/" + my_File).getLink();
my_url = new URL (my_link);
conn = my_url.openConnection();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} catch (DbxException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Related

[ANDROID]How to get HTML source from a URL(using WEBAPI for uTorrent)

I need to get a simple string out of the HTML code in a url.
FwyKvZJSZMLdgAlEuMvw7v_s9VhasprI-47KeavMegGJlvAC5ZLwng5gEFgAAAAA .
This is how it looks like. All I need is the string from the start.
This is the URL request I use to reach the code.
http://username:password#IP:8080/gui/token.html
The answers I found were either way too complicated or straight up didnt work (HTTPClient is now deprecated :( ).
This is what I have, but sadly it always returns java.io.FileNotFoundException: http://www.google.com and it does that on every website.
This is the code for it:
try {
System.out.println("TEST");
con = (HttpURLConnection) new URL("http://username:password#IP:8080/gui/token.html").openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.setDoInput(true);
System.out.println(con.getOutputStream().toString());
InputStream response = con.getInputStream();
System.out.println("RMessage" + con.getResponseMessage());
con.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
con.setRequestProperty("Accept","*/*");
BufferedReader reader = new BufferedReader(new InputStreamReader(response));
for (String line; (line = reader.readLine()) != null; ) {
System.out.println(line + "NEKAJ SE JE ZGODILO V PRIDOBITVI");
}
reader.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
The link works alright in my Chrome App on my device.
Getting the source of something like Facebook.com or Google works alright too. I'm super confused.
EDIT: Printed the stacktrace:
10-26 11:45:52.816 3341-3721/com.example.davidvuckovic7.utorrentclient W/System.err: java.io.FileNotFoundException:
To avoid posting a separate thread for it, is there a way to customize URL's? To get user input username and password or user input IP?
Apparently I need to fix my cookies. Because browsers handle cookies automatically and my app doesn't, it causes issues. Tokens and cookies are apparently connected.
Now on to the next problem,

BufferedReader and InputStreamReader from URL

I'm a new student working on an android application. The application is almost done and works fine.
The app uses a property list to generate it's content. At this moment it uses a .plist file located in the assets folder. Ideally I want this .plist file to be retrieved from an URL. However i'm stuck on this part for a few days now.
Could you please advise me in how to realise retrieving and using the file from an URL. Any advice is welcome!
In my code we see how I currently read the .plist file. I don't think the parsing of the response is required info for my question:
public class PListHelper {
/**
* PlayList reader from assets
*
* #return string of p-list file
*/
public static String readPlayListFromAssets(Context context) {
StringBuffer sb = new StringBuffer();
BufferedReader br=null;
try {
br = new BufferedReader(new InputStreamReader(context.getAssets().open("restaurant.plist")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException ex) {
ex.printStackTrace();
}
}
Log.i("Main", "input: "+sb.toString());
return sb.toString();
}
Have a look at URLConnection
Also, in the future, avoid using .plist as it something specific to ios and osx. By using another format (like json) you won't have to implement your own parsing.

How to use webview or open URL in AndEngine - Android

I'm utilizing a game engine called AndEngine (which I'm completely new to) in my Android app. I need to load a different URL from the application based on what position an onscreen joystick is in (uploading to a .cgi server). The dilemma is that I cannot open a URL connection! This may seem simple, but I've looked everywhere, tried multiple solutions and nothing's worked. In basic Android, I've always used a WebView (loadUrl() method), and it worked well. However, I have no idea to how to create a webview while also using AndEngine. My preference is that the connection did not show (loaded underneath the AndEngine scene?) because I will need the screen for other things. I've also tried other solutions. I just tried this code, but when I checked the server, nothing was opened:
#Override
public void onLoadResources() {
//methods n/a to this question
try {
URL url = new URL(setUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return scene; // AndEngine return statement
}
private void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
**I've tried using the HTTPConnection class before (without AndEngine) to open up a URL, but to no avail. So it may be that I was just doing something wrong here. Using AndEngine GLES2. If more info is needed, let me know (this is my first question on SO).
Also tried setting up my .xml layout on AndEngine using
#Override
protected int getLayoutID() {
return R.layout.main;
}
but it says: "The method getLayoutID() of type Control must override or implement a supertype method"
Edit in response to Nicolas Gramlich: Internet permissions were set and compiler was originally at 1.6. Still don't know what the issue is.
xml
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
Set java compiler compliance to 1.6
I solved my issue. I had to run all network operations on a thread separate from the main one (else it will throw a NetworkOnMainThread exception). I don't know why nothing else worked, but this did the trick! Here I'm creating a new thread with the action I want to perform, and then starting it after exceptions are taken care of. I found my answer here
new Thread(new Runnable() {
public void run() {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("your_url");
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

Need an example of HttpResponseCache in Android

Hi I am trying to use the HttpResponseCache introduced in Android 4.The docs do talk clearly about how to install the cache but I am at a complete loss on how to cache Images downloaded from the net.Earlier I was using the DiskLruCache to cache them. Would anyone point me towards some examples of working code where HttpResponseCache has been used..
Edit:- Can someone tell me what I am doing wrong here:-
MainActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
final File httpCacheDir = new File(getCacheDir(), "http");
try {
Class.forName("android.net.http.HttpResponseCache")
.getMethod("install", File.class, long.class)
.invoke(null, httpCacheDir, httpCacheSize);
Log.v(TAG,"cache set up");
} catch (Exception httpResponseCacheNotAvailable) {
Log.v(TAG, "android.net.http.HttpResponseCache not available, probably because we're running on a pre-ICS version of Android. Using com.integralblue.httpresponsecache.HttpHttpResponseCache.");
try{
com.integralblue.httpresponsecache.HttpResponseCache.install(httpCacheDir, httpCacheSize);
}catch(Exception e){
Log.v(TAG, "Failed to set up com.integralblue.httpresponsecache.HttpResponseCache");
}
}
TheMainListFrag gf=(TheMainListFrag) getSupportFragmentManager().findFragmentByTag("thelistfrags");
if(gf==null){
gf=TheMainListFrag.newInstance();
FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
ft.replace(R.id.thelefty, gf,"thelistfrags");
ft.commit();
}
}
Then in the loader of TheMainListFrag, I do the below:-
public ArrayList<HashMap<String,String>> loadInBackground() {
String datafromServer = null;
ArrayList<HashMap<String,String>> al = new ArrayList<HashMap<String,String>>();
try {
String url = "someurl";
HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
InputStream is = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
datafromServer=sb.toString();
Log.v("fromthread",datafromServer);
// etc
//etc
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
Log.v("fromthread", e.getClass() + "--" + e.getMessage());
}
return al;
}
When i am connected to internet, it works fine, and in the directory http-the cache directory named above, i can see the files too. But when I am not connected to the internet, the data refuses to load.
When i load images from the net, i see the cache files named as .tmp , which i believe are termed as dirty as per DiskLruCache.
Please let me know if there is any other info that you want me to provide
From the section Force a Cache Response on the HttpResponseCache documentation:
Sometimes you'll want to show resources if they are available
immediately, but not otherwise. This can be used so your application
can show something while waiting for the latest data to be
downloaded. To restrict a request to locally-cached resources, add the
only-if-cached directive:
try {
connection.addRequestProperty("Cache-Control", "only-if-cached");
InputStream cached = connection.getInputStream();
// the resource was cached! show it
} catch (FileNotFoundException e) {
// the resource was not cached
}
This technique works even better in situations where a stale response
is better than no response. To permit stale cached responses, use the
max-stale directive with the maximum staleness in seconds:
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
When you enable HttpResponseCache, all HttpUrlConnection queries will be cached. You can't use it to cache arbitrary data, so I'd recommend keep using DiskLruCache for that.
In my case HttpResponseCache wasn't actually caching anything. What fixed it was simply:
connection.setUseCaches(true);
(This must be called on the HttpURLConnection before establishing connection.)
For finer grained control, max-stale can be used as Jesse Wilson pointed out.

json data send using post in android

i want to send my data in form of json to server using post method in android.
here is my format |data1|data2|data3|<>|data11|data22|data33
hope some example since i difficult to catch the procedure of post method.
Anyidea?
Edit:
my json format |data1|data2|data3|<>|data11|data22|data33|
where each data is a plain text (text get from database)
how can create it??
This blog post seems to talk about just that.
Post JSON Using Android And HttpClient
Edit: I saw your reply. Here's how. Hope this does the trick :)
public static void main(String[] args) {
File file = new File("<path to json file>");
FileInputStream fis;
String json = "";
try {
fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
json += dis.readLine();
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Essentially after this you would create the string entity to send
StringEntity st = new StringEntity(json.toString());
Then just follow the steps in that link
Haha, edit for your 2nd question: Just create a string with the text from the database. Thats all there is to it. Then create a StringEntity like the one above.

Categories

Resources