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.
Is there a way to send android local HTML forms via ajax to remote php server? (local means the files are in my device) My scenario is this: In my app, I have an html files in my android device and is loaded in a webview, i also have the javascript file in my device. What i want to do is to send the html forms data to a remote server. In my current situation, its not sending any data, I've check the javascript and php and the code is fine, and it's working on iOS version of the app. I've tried other workarounds and what I've observed is that, when i load html file in webview using local files (e.g. webview.loadUrl("file://"+ Environment.getExternalStorageDirectory()+"/android_asset/list.html"), the android is looking for all other related files (e.g. formsprocessor.php) locally, though in javascript/ajax all necessary arguments in it's functions are supplied properly. The errors i've encountered are: FileNotFound: content://packagename.com/formsprocessor.php & Unknown chronium error: -6.
Is there a way or what is the best way to do this?
Thanks, Clint.
This solve my problem:
Used a javascripthandler, and in my javascript i call the function from the handler. So basically, the android handled the upload of data to server using httppost. Here's the codes;
the handler:
final class IJavascriptHandler{
IJavascriptHandler(){}
public void sendJSONToAndroid(String text){
if(!Config.canConnect((ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE), home) && dialogNoConnFlag == false) {
dialogNoConnFlag = true;
Config.notificationMsg(Config.ERRORNOCONN,home, Config.TITLE1 + " " + Config.TITLE6);
return;
}
try {
Log.v("SendToServer","Send JSON to Server");
String url = "";
JSONObject json_data = new JSONObject(text);
JSONArray names= json_data.names();
JSONArray values = json_data.toJSONArray(names);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for(int i = 0 ; i < values.length(); i++){
Log.v("Good",names.getString(i).toString());
if(names.getString(i).equals("url")) {
url = json_data.getString(names.getString(i)).toString();
}
nameValuePairs.add(new BasicNameValuePair( names.getString(i).toString(), json_data.getString(names.getString(i)).toString()));
}
Config.uploadToServer(nameValuePairs, url);
}
catch (JSONException e)
{
Config.notificationMsg(Config.ERRORMSG + e.getMessage(), (Activity) home, Config.TITLE1 + " " + Config.TITLE6);
}
}
}
the httppost:
public static String uploadToServer(List<NameValuePair> nameValuePairs, String url){
if(Session.isordinaryHost)
{
httpclient = new DefaultHttpClient();
}
else
{
httpclient = new MyHttpClient().getNewHttpClient();
((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(
new AuthScope(Session.siteIp, 443),
new UsernamePasswordCredentials(Session.siteUsername, Session.sitePassword));
}
httppost = new HttpPost(url);
try
{
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
EntityUtils.toString(entity);
}
catch (ClientProtocolException e)
{
return e.getMessage();
}
catch (IOException e)
{
return e.getMessage();
}
return null;
}
the javascript:
function CheckCompleteRecords() {
DB.transaction(function(tx) {
tx.executeSql(SelectCompleteForUploadStatement, [], function(tx, result) {
Dataset = result.rows;
for (var i = 0, item = null; i < Dataset.length; i++) {
item = Dataset.item(i);
var a = createJSON(item['FormName'],item['UserID'],item['Image1'],item['Image2'],item['Image3'],item['Image4'],item['Image5'],item['Field1'],item['Field2'],item['Field3'],item['Field4'],item['Field5'],item['Field6'],item['Field7'],item['Field8'],item['Field9'],item['Field10'],item['Field11'],item['Field12'],item['Field13'],item['Field14'],item['Field15'],item['Field16'],item['Field17'],item['Field18'],item['Field19'],item['Field20'],item['Field21'],item['Field22'],item['Field23'],item['Field24'],item['Field25'],item['Field26'],item['Field27'],item['Field28'],item['Field29'],item['Field30'],item['Field31'],item['Field32'],item['Field33'],item['Field34'],item['Field35'],item['Field36'],item['Field37'],item['Field38'],item['Field39'],item['Field40'],item['Field41'],item['Field42'],item['Field43'],item['Field44'],item['Field45'],item['Field46'],item['Field47'],item['Field48'],item['Field49'],item['Field50'],item['Field51'],item['Field52'],item['Field53'],item['Field54'],item['Field55'],item['Field56'],item['Field57'],item['Field58'],item['Field59'],item['Field60'],item['Field61'],item['Field62'],item['Field63'],item['Field64'],item['Field65'],item['Field66'],item['Field67'],item['Field68'],item['Field69'],item['Field70'],item['Field71'],item['Field72'],item['Field73'],item['Field74'],item['Field75'],item['Field76'],item['Field77'],item['Field78'],item['Field79'],item['Field80'],item['Field81'],item['Field82'],item['Field83'],item['Field84'],item['Field85'],item['Field86'],item['Field87'],item['Field88'],item['Field89'],item['Field90'],item['Field91'],item['Field92'],item['Field93'],item['Field94'],item['Field95'],item['Field96'],item['Field97'],item['Field98'],item['Field99'],item['Field100'],item['CurrentDateTime'],item['Geolocation'],item['BarCode']);
window.cpjs.sendJSONToAndroid(a);
showStuff('SendServerBtn');
window.location = "senttoserver://app_action";
}
});
});
}
I have big problems with getting the certificates running under android.
I have an android client which connects to a WCF-Service.
I think the problem is, that the certificates are not transfered. I get an error message:
403 forbidden (in the response). I really hope you can help me.
=> in my android client
In internet explorer, it works just fine => status 200
I found this article:
http://android-developers.blogspot.de/2012/03/unifying-key-store-access-in-ics.html
"A common use of the private key is for SSL client authentication. This can be implemented by using an HttpsURLConnection with a custom X509KeyManager that returns the PrivateKey retrieved from the KeyChain API. The open source Email application for ICS uses KeyChain with an X509ExtendedKeyManager. To learn more, have a look at the source code (in SSLUtils.java)."
I have checked out the SSLUtils class and I am trying to use it.
Here is some code:
private void setHttpsAdvanced() {
HostAuth ht = new HostAuth();
ht.mPort = 443;
ht.mClientCertAlias = "jensZert";
HttpParams params = getHttpParams();
MyThreadSafeClientConnManager ccm = MyThreadSafeClientConnManager
.newInstance(params, true, 443);
try {
MyThreadSafeClientConnManager.makeScheme(true, false,
ht.mClientCertAlias);
ccm.registerClientCert(getApplicationContext(), ht);
// checkCertificate(ht.mClientCertAlias);
} catch (CertificateException e) {
Log.d(TAG, e.getMessage());
e.printStackTrace();
}
this.httpclient = new DefaultHttpClient(ccm, params);
connectionInfo = this.getConnectionInfo();
this.url = String.format("%1$s://%2$s/%3$s/%4$s",
connectionInfo.Protocol, connectionInfo.ServerName,
connectionInfo.WebserviceName, connectionInfo.Path);
httpGet = new HttpGet(url);
}
private String callTheWebserviceCertificate() {
this.setupClient();
String result = "";
HttpResponse response = null;
try {
response = (HttpResponse) this.httpclient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
result = e.getMessage() + "\n";
for (StackTraceElement el : e.getStackTrace()) {
result += el.toString() + "\n";
}
Log.d(TAG, result);
}
return result;
}
greetings,
jens
I´m creating an android application that stores data in CouchDB, and I need to create a database from the android application. I need to execute the command "curl-X PUT http://user:passwd#127.0.0.1:5984/myDataBase" with java methods.
I have implemented the following functions:
public static boolean createDatabase(String hostUrl, String databaseName) {
try {
HttpPut httpPutRequest = new HttpPut(hostUrl + databaseName);
JSONObject jsonResult = sendCouchRequest(httpPutRequest);
return jsonResult.getBoolean("ok");
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
private static JSONObject sendCouchRequest(HttpUriRequest request) {
try {
HttpResponse httpResponse = (HttpResponse) new DefaultHttpClient().execute(request);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String resultString = convertStreamToString(instream);
instream.close();
JSONObject jsonResult = new JSONObject(resultString);
return jsonResult;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I call the function by:
createDatabase("http://user:passwd#127.0.0.1/","myDataBase");
but there is no result. I think the problem is in user:passwd because in "admin party" mode the funcion works fine calling by:
createDatabase("http://127.0.0.1/","myDataBase");
I had the same problem -> you have to use the HTTP Authentication in the header.
So just add this header lines to your request:
private static void setHeader(HttpRequestBase request) {
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
request.setHeader("Authorization", "Basic base64(username:password)");
}
keep in mind that you have to encode the phrase "username:password" with base64.
this looks something like this:
request.setHeader("Authorization", "Basic 39jdlf9udflkjJKDKeuoijdfoier");
You could have a look at this blogpost on libcouch-android. It has some nice features that really support Android development with CouchDB. For example automatically creating databases and passwords for applications, so users have transparent usage of CouchDB (if wanted).
Also, it is offering access to the RPC methods of CouchDB, so you can start and stop the DB from your application's lifecycles.
Regarding security, I just had this summed up here in this thread.
I have written a web application to run on Google AppEngine using the Restlet framework, communicating using json with web clients. Those work as expected. However, one specific resource written to provide response to an Android client doesn't work when accessed through Android. However, it does work when accessed through a web browser (I do not send the request parameters from the browser and thus get a 400 which is ok in this case).
This code works when running on the DevAppServer:
public class PlayResource extends ServerResource {
private final float SCOREBASE = 1000.0F;
#Get
#Post
public JsonRepresentation play() {
try {
JsonRepresentation rep = new JsonRepresentation(getRequestEntity());
JSONObject inputJson = rep.getJsonObject();
JSONObject outputJson = new JSONObject();
String country = inputJson.optString("country");
outputJson.put("country", doSomething("country",country));
......
......
return new JsonRepresentation(outputJson);
} catch (IOException e) {
try {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return new JsonRepresentation(
new JSONObject()
.put(Messages.TYPE_ERROR, Messages.BAD_REQUEST));
} catch (JSONException e2) {
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
} catch (JSONException e) {
try {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return new JsonRepresentation(
new JSONObject()
.put(Messages.TYPE_ERROR, Messages.BAD_FORMAT));
} catch (JSONException e2) {
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
}
}
}
and the client Android device is running this code:
Client client = new Client(Protocol.HTTP);
try {
JsonRepresentation requestJSON = new JsonRepresentation(new JSONObject()
.put("country", country.trim())
);
Request req = new Request(Method.GET,"http://****.appspot.com/resource/play",requestJSON);
Response resp = client.handle(req);
String res = resp.getEntity().getText();
JSONObject resultJSON = new JSONObject(res);
Running this request just hangs the Android client, the server doesn't write any log messages whatsoever suggesting the request doesn't arrive there.
It seems that it's more a Appengine/Java issue than an android issue, but...let's try something else:
instead of using Client and the stuff u are using, first just try to see what the server responds to the simplest connection (as you do in a web browser):
URL url;
try {
url = new URL("http://yourappid.appspot.com/resource/play");
String content = (String) url.getContent();
System.out.println(content);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If it works and you get your expeted 400, if so...try to send an httppostrequest with the data...like this:
HttpClient client = new DefaultHttpClient();
HttpUriRequest httpRequest = new HttpPost("http://yourappid.appspot.com/resource/play");
//set the content type to json
httpRequest.setHeader("Content-Type", "application/json");
//get and work with the response
HttpResponse httpResponse = client.execute(httpRequest);
Let me know if the answer was useful