How to use webview or open URL in AndEngine - Android - 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();

Related

Reading a DropBox Text File

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();
}

Get current date and time from Google in Android

I have some experience in Android application development. Now we developed an Android application where we need the exact date and time from Google or the internet. Already I test some code from Stack Overflow and from some other sites, but it did not work correctly. The app crashed. Can anyone help me?
Try this:
private long getTime() throws Exception {
String url = "https://time.is/Unix_time_now";
Document doc = Jsoup.parse(new URL(url).openStream(), "UTF-8", url);
String[] tags = new String[] {
"div[id=time_section]",
"div[id=clock0_bg]"
};
Elements elements= doc.select(tags[0]);
for (int i = 0; i <tags.length; i++) {
elements = elements.select(tags[i]);
}
return Long.parseLong(elements.text() + "000");
}
Gradle:
compile 'org.jsoup:jsoup:1.10.2'
This is enough to get what you wanted:
Using the HttpGet, Client and Response, I manage to get a server's current time from the response Date Header. I can call this all the times I want and will get confident responses (Google is almost 100% available and I can trust on getting correct Date and Time)
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("https://google.com/"));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
String dateStr = response.getFirstHeader("Date").getValue();
//Here I do something with the Date String
System.out.println(dateStr);
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}catch (ClientProtocolException e) {
Log.d("Response", e.getMessage());
}catch (IOException e) {
Log.d("Response", e.getMessage());
}
ou can get time from internet time servers using the below program
import java.io.IOException;
import org.apache.commons.net.time.TimeTCPClient;
public final class GetTime {
public static final void main(String[] args) {
try {
TimeTCPClient client = new TimeTCPClient();
try {
// Set timeout of 60 seconds
client.setDefaultTimeout(60000);
// Connecting to time server
// Other time servers can be found at : http://tf.nist.gov/tf-cgi/servers.cgi#
// Make sure that your program NEVER queries a server more frequently than once every 4 seconds
client.connect("nist.time.nosc.us");
System.out.println(client.getDate());
} finally {
client.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
1.You would need Apache Commons Net library for this to work. Download the library and add to your project build path.
(Or you can also use the trimmed Apache Commons Net Library here : https://www.dropbox.com/s/bjxjv7phkb8xfhh/commons-net-3.1.jar. This is enough to get time from internet )
2.Run the program. You will get the time printed on your console.

Android: how can I make an HTTP HEAD request?

I would like to make a simple HTTP HEAD request, without keep-alive.
How can I do that in Android?
using HttpClient:
As njzk2 suggested, with HttpClient() it's very straightforward:
HttpResponse response = new HttpClient().execute(new HttpHead(myUrl));
However there is a problem with not being able to close the connection. Usually on the HttpClient, you would get the entity using:
HttpEntity entity = response.getEntity();
and then you would get the input stream from the entity
InputStream instream = entity.getContent();
...
instream.close();
and by closing the input stream, the connection would close.
However, in the case of a HEAD request, the entity appears to be null (possibly because HEAD requests don't return the body in the response), so the input stream cannot be fetched and closed and the connection doesn't close either.
In the last edit to his answer, njzk2 is suggesting to use AndroidHttpClient, which is a more recent implementation (API 8) of HttpClient and it actually has a close() method. I haven't used it but I guess it will work fine. However, as the Android development team suggests, the HttpUrlConnection should be the preferred Android client to use.
using HttpUrlConnection:
Actually it seems quite easy to make HEAD requests using HttpUrlConnection and make sure that the connection closes:
HttpURLConnection urlConnection = null;
System.setProperty("http.keepAlive", "false");
try {
URL url = new URL(stringUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("HEAD");
urlConnection.getInputStream().close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
Trivially :
HttpResponse response = new AndroidHttpClient().execute(new HttpHead(myUrl));
Typically you'll use the same AndroidHttpClient for several connections, then call close on it.
For ordinary Java and Android
I am using some standard Java code to test the existence of a resource and in the same time to check whether a resource has been changed, provided the parameter if_modified_since is non-zero.
URL url = new URL(adr);
try {
URLConnection con = url.openConnection();
con.setIfModifiedSince(if_modified_since);
if (con instanceof HttpURLConnection) {
/* Workaround for https://code.google.com/p/android/issues/detail?id=61013 */
con.addRequestProperty("Accept-Encoding", "identity");
((HttpURLConnection) con).setRequestMethod("HEAD");
int response = ((HttpURLConnection) con).getResponseCode();
if (response == HttpURLConnection.HTTP_UNAVAILABLE)
return false;
if (response == HttpURLConnection.HTTP_NOT_MODIFIED)
return false;
}
if (if_modified_since != 0) {
long modified = OpenOpts.getLastModified(con);
if (modified != 0 && if_modified_since >= modified)
return false;
}
InputStream in = con.getInputStream();
in.close();
return true;
} catch (FileNotFoundException x) {
return false;
} catch (UnknownHostException x) {
return false;
} catch (SocketException x) {
return false;
}
Interestingly the code needs a con.getInputStream() and I don't get some errors here. But I needed some helper code, to also cater for URIs that point to JARs. The helper code is:
private static long getLastModified(URLConnection con)
throws IOException {
if (con instanceof JarURLConnection) {
return ((JarURLConnection) con).getJarEntry().getTime();
} else {
return con.getLastModified();
}
}
The code can be further optimized by some specialization if the
URI is schema file: , one can then directly do File.exists() and File.getLastModified().
We do not throw a ServiceUnvailable exception here, we basically assume that the outer code would catch an IOException and then assume a false
result of the getHead().

Android http testing with Robolectric

I have an Android app where the main part of the app is the APIcalls.java class where I make http requests to get data from server an display the data in the app.
I wanted to create unit test for this Java class since it's the most part of the app. Here is the method for getting the data from server:
StringBuilder sb = new StringBuilder();
try {
httpclient = new DefaultHttpClient();
Httpget httpget = new HttpGet(url);
HttpEntity entity = null;
try {
HttpResponse response = httpclient.execute(httpget);
entity = response.getEntity();
} catch (Exception e) {
Log.d("Exception", e);
}
if (entity != null) {
InputStream is = null;
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
} catch (IOException e) {
throw e;
} catch (RuntimeException e) {
httpget.abort();
throw e;
} finally {
is.close();
}
httpclient.getConnectionManager().shutdown();
}
} catch (Exception e) {
Log.d("Exception", e);
}
String result = sb.toString().trim();
return result;
I thought I can make simple API calls from the tests like this:
api.get("www.example.com")
But every time I make some http calls from the tests, I get an error:
Unexpected HTTP call GET
I know I am doing something wrong here, but can anyone tell me how can I properly test this class in Android?
Thank you for all your answers but I found what I was looking for.
I wanted to test real HTTP calls.
By adding Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
you tell Robolectric not to intercept these requests and it allows you to make real HTTP calls
Robolectric provides some helper methods to mock http response for DefaultHttpClient. If you use DefaultHttpClient without using those methods, you would get a warning message.
Here is an example of how to mock http response:
#RunWith(RobolectricTestRunner.class)
public class ApiTest {
#Test
public void test() {
Api api = new Api();
Robolectric.addPendingHttpResponse(200, "dummy");
String responseBody = api.get("www.example.com");
assertThat(responseBody, is("dummy"));
}
}
You can find more examples by looking at Robolectric's test codes.
I answered another version of this same question, but...
What you have here is not using anything from Android, so Robolectric is basically irrelevant. This is all standard Java and the Apache HTTP library. You simply need a mocking framework and dependency injection to simulate the HttpClient (see my other answer for links). It doesn't have network access while unit testing, and so it fails.
When testing classes that use parts of the Android framework, you can use Robolectric (or similar) to mock or simulate Android.jar since your unit testing framework isn't going to have access to that either.

Do I need to call HttpURLConnection.disconnect after finish using it

The following code basically works as expected. However, to be paranoid, I was wondering, to avoid resource leakage,
Do I need to call HttpURLConnection.disconnect, after finish its usage?
Do I need to call InputStream.close?
Do I need to call InputStreamReader.close?
Do I need to have the following 2 line of code : httpUrlConnection.setDoInput(true) and httpUrlConnection.setDoOutput(false), just after the construction of httpUrlConnection?
The reason I ask so, is most of the examples I saw do not do such cleanup. http://www.exampledepot.com/egs/java.net/post.html and http://www.vogella.com/articles/AndroidNetworking/article.html. I just want to make sure those examples are correct as well.
public static String getResponseBodyAsString(String request) {
BufferedReader bufferedReader = null;
try {
URL url = new URL(request);
HttpURLConnection httpUrlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpUrlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
int charRead = 0;
char[] buffer = new char[1024];
StringBuffer stringBuffer = new StringBuffer();
while ((charRead = bufferedReader.read(buffer)) > 0) {
stringBuffer.append(buffer, 0, charRead);
}
return stringBuffer.toString();
} catch (MalformedURLException e) {
Log.e(TAG, "", e);
} catch (IOException e) {
Log.e(TAG, "", e);
} finally {
close(bufferedReader);
}
return null;
}
private static void close(Reader reader) {
if (reader != null) {
try {
reader.close();
} catch (IOException exp) {
Log.e(TAG, "", exp);
}
}
}
Yes you need to close the inputstream first and close httpconnection next. As per javadoc.
Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.
Next two questions answer depends on purpose of your connection. Read this link for more details.
I believe the requirement for calling setDoInput() or setDoOutput() is to make sure they are called before anything is written to or read from a stream on the connection. Beyond that, I'm not sure it matters when those methods are called.

Categories

Resources