I am trying to get my Java program to send a GET request to the following (pseudo) PHP file:
www.domain.com/example.php
Here is the PHP script:
<?php
include "dbcredentials.php";
$query = "INSERT INTO accesscode (id) VALUES ('" . $_GET['auth'] . "')";
$result = mysql_query($query) or die(mysql_error()); // Check if query was successful
print ($_GET['auth']);
?>
The above php is fairly self explanatory. When a GET request is received, it prints the content of the request to the page and also adds it in the column "ID" in table named "accesscode".
Therefore if typing "www.domain.com/example.php?auth=Brad+Pitt", the PHP file will print Brad Pitt and add that to the table "accesscode".
Okay, simple enough. Except I want my Java program to be able to send a GET request too. So I devised the following function which is called by new phpGET().execute():
public class phpGET extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://domain.com/example.php?auth=David+Cameron");
URLConnection connection = url.openConnection();
connection.connect();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
Now just to confirm, the above does not catch an error. But for some reason, it must fail to send the GET request (http://domain.com/example.php?auth=David+Cameron) to the php file, on the basis that David Cameron is not added to the database after the function is called, as is intended.
I confirm I have the following Android manifest permissions:
<uses-permission android:name="android.permission.INTERNET" />
I'm pretty stumped on this one; any ideas?
Additional information: I am using Windows 7 x86, the latest Android Studio and testing on a Samsung Galaxy S5.
Also please note, I am aware, and it has been brought to my attention, that essentially I should be using PDO for database access, and that I should be taking additional action to prevent MySQL injection vulnerabilities that the code is riddled with. I would like to assure you that I intend on doing so upon solving the central problem discussed herein.
Okay,
So I'm not exactly too sure how good of a solution this is, but irrespective, it does exactly what I set out to achieve. I was able to successfully send a PHP GET request to the .php file using the following:
public class phpGET extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://www.domain.com/example.php?auth=David+Cameron");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
is.close();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
replace
URL url = new URL("http://domain.com/example.php?auth=David+Cameron");
URLConnection connection = url.openConnection();
connection.connect();
with
URL obj = new URL("http://domain.com/example.php?auth=David+Cameron");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
Related
I have a microprocessor that hosts a webServer and webpage over wifi and interacts with an Android app. The webpage has a submit button eg HTML
<form action="/RUNME" method="POST">
<input type="submit" value="Run Me">
</form>\
When the button is pressed on the opened webpage on the Android device it prompts the server to process its runMe method which executes on a microprocessor.
The microprocessors c code includes this line which when receiving a POST request executes the method runMe
server.on("/RUNME",HTTP_POST,runMe);
I need to achieve the same behaviour from within an android app equivalent to pressing the submit button or
running the runMe routine on the webserver.
The method has to receive the URL eg http://www.xxx.xxx.xx.xx and some argument "/RUNME" or "Run Me". I am unsure of the formatting of the arguments nor which method to use.
String websiteUrl = http://www.xxx.xxx.xx.xx;
URL url = new URL(websiteUrl);
HttpURLConnection connection = url.openConnection();
connection.setDoOutput(true);//Set output method to POST
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(websiteUrl + "/RUNME");
out.close();
Example code block part of my Asynchronous Task
#Override
protected Integer doInBackground(String[] arg0) {
try {
url = new URL(arg0[0]);
urlconn = (HttpURLConnection)url.openConnection();
urlconn.setAllowUserInteraction(false);
urlconn.setDoOutput(true);
urlconn.setIfModifiedSince(0);
urlconn.setUseCaches(true);
urlconn.setConnectTimeout(3000);
urlconn.setReadTimeout(3000);
urlconn.connect();
responseCode =urlconn.getResponseCode();
if(responseCode==HttpURLConnection.HTTP_OK){
//POST the HTTP request how to get the same behaviour as pressing the webpage submit buttom
//How do you do this what method should you use and what arguments that include the url, arg0[0] and /RUNME
urlconn.????
}
urlconn.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseCode;
}
I am currently building an app that saves the user's blog post in Firestore server. Everything is working fine, but I found out that the post was not uploaded under the unstable internet connection.
I tried to set a timeout to the Firestore instance, but it seems like there's no timeout option for Firestore library. The problem is, because there's no timeout setting, the app doesn't know when to dismiss the uploading screen (Spinner dialog).
I was thinking about creating a Handler or Observable or Thread and setting the timeout manually. After the specified timeout period, let the app dismiss the uploading screen. However, Firestore client will keep retrying the upload in the background even after the timeout. So this approach won't be suitable for this case...
Is there any solution for this? If I can set the timeout for the Firestore client itself, meaning letting the client to call onFailure() after the given timeout period, I can just save the post as draft in the local storage and try it again when the device is back to stable connection.
Firestore will immediately add the document to its local cache. It will then try to synchronize that document with the server. To detect whether it will be able to do so, have a look at Gastón's answer.
To detect when the document has been written to the server, use a SuccessListener. This example from the Firestore documentation on adding documents shows how:
// Add a new document with a generated id.
Map<String, Object> data = new HashMap<>();
data.put("name", "Tokyo");
data.put("country", "Japan");
db.collection("cities")
.add(data)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
The best way of doing this is attaching a boolean that will let you know if you have internet before doing something (this is just to dismiss your spinner, as firestore has offline features like realtime database)
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
so you should check first if you have an active connection , this method will ping google.com and check for internet connection, if is not reachable after 1.5 seconds it will return false
so you should do something like this (pseudocode)
if(hasActiveInternetConnection)
doyourfirebaseuploadstuff
else
spinner.dismiss()
Toast(please check your internet connection and try again)
Remember to add your internet permissions in your manifest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
EDIT:
Another cool method and maybe more readable for someones can be this one
public boolean isInternetWorking() {
boolean success = false;
try {
URL url = new URL("https://google.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.connect();
success = connection.getResponseCode() == 200;
} catch (IOException e) {
e.printStackTrace();
}
return success;
}
it just works like the other one , instead that this will just wait for 10 seconds untill it returns the internet status
My android app used the old microsoft Translator very well but I am having
problems getting the app to work with the new Cognitive Services.
First I got a new azure translation account that has the following values
(these are not the real values)
Name: MYTranslateAcct
Resource group: translate
subscription ID: 981h5ce7-7ac7-4f6f-b4a5-ff04dc9e4266
key1 d122230418a8479ab5c06f2f1fca664c
key2 39c1f187o9814f4e983jba9eedd2e2c7
My first step is to try to get a token. Microsoft has docs on doing
this in JAVA but not in an Android environment. I dug around and have
put together some code but it is not working. One problem is that the
docs use terms that I don't have in my account such as "app-id" and
"key". I don't have those things - I just have the list of values
above.
Here is my code . . .
class translateMessage extends AsyncTask<Void, Void, String>
{
String retString;
String inString = null;
translateMessage(String inString) { this.inString = inString; }
#Override
protected String doInBackground(Void... arg0)
{
try
{
String key = "881b5ce7-9ac7-4f6f-b4a5-ff04dc9e3199";
String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
authConn.setRequestMethod("POST");
authConn.setDoOutput(true);
authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
IOUtils.write("", authConn.getOutputStream(), "UTF-8"); //following line of code gets the exception . . .
String token = IOUtils.toString(authConn.getInputStream(), "UTF-8"); //this blows
}
catch (Exception e)
{
String myString = e.getMessage();
String aString = "look at e";
}
return retString;
}
#Override
protected void onPostExecute(String result)
{
String debugStr = result;
translation.setText(result);
}
}
Following is the exception . . .
java.io.FileNotFoundException:https://api.cognitive.microsoft.com/sts/v1.0/issueToken
What am I doing wrong?
Is anyone aware of any working Android java code using the new services?
I posted this on Azure support and someone called me within an hour. I was passing the wrong key. When you get a translate cognitive account you get Key1 and Key2. Either of them will work. So the code is a useful example of working code that will get a token.
I'm developing a course selection app for a university. Students must register to application. I'm using SQLlite by using db helper, my table contains studentID,password,name etc.
My question is this sqlite db stays on only local ? I mean, how can i reach student table on multiple device, read and write at the same time. When it puts on the play store thousand of student will use it.
Which technologies should i use, where should i put the db ?
I'm really confused about it, thanks for advance.
By sqlite it is not possible. You have to create the database on server. For that thing you can use mysql, oracle etc. So from server n number of students can access the data.
There are many times when your Android app will need to fetch data from the internet, to provide users with fresh information and/or data. There are different ways your app could achieve this. You could set up your own web service/API, or you could be fetching from an already existing service/API.
1) To get the data from API Luckily, there is a class just for this, called AsyncTask. From the Android documentation, AsyncTask facilitates the proper and easy use of the UI thread, by allowing the performance of background operations, and publishing the results on the UI thread without the need for manipulating threads and handlers. In simple words, AsyncTask handles all the complexity for you.
2) To make use of the AsyncTask features, you must subclass it, and provide 3 generic types, called Params, Progress and Result. Params refers to the parameters that would be parsed to your Task, Progress refers to the progress indicator/counter type, and Result is what would be returned on completion of the task. AsyncTask has 4 important methods, onPreExecute (what to do before the expensive task begins), doInBackground (the actual expensive operation goes in here), onProgressUpdate (what to do to show progress), and onPostExecute (what to do when the task is complete).
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
String email = emailText.getText().toString();
// Do some validation here
try {
URL url = new URL(API_URL + "email=" + email + "&apiKey=" + API_KEY);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
}
}
Read this tutorial to use this feature: http://www.androidauthority.com/use-remote-web-api-within-android-app-617869/
Also see this documentation: http://developer.android.com/reference/android/os/AsyncTask.html
I am trying to send information to my company's server. Basically when I enter a URL pointing to it and connect to it in a browser, it takes parameters contained in the URL and puts them in a database. Again when done in a browser, it works. However, I would like to be able to send this information every time an event of importance (like scanning a qr code in our app) happens, and I want it to be done in the background (without the user knowing.)
We have tried ConnectionFactory, HTTPRequests etc etc, nothing has worked for us so far.
I am sure there is a simple way to go about this.
Can anyone provide us with the few elusive lines of code to help us do what we want to do??
Thanks alot!
Edit:
Okay here is some code we tried using (one of many code snippets) but it did not work:
public class ConnectionThread extends Thread{
String URL;
public ConnectionThread(String URL) {
this.URL = URL;
}
public void run() {
ServerCalls sc = new ServerCalls(); // This is for generating the URL
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(sc.fillParameters(URL));
if (connDesc != null)
{
HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
}
}
}
and we call
new ConnectionThread(barcode).start()
when we need it to send the info to the server.
For opening the url you can use
javax.microedition.io.HttpConnection Package.
And here is the code how to go about that....
HttpConnection connection=(HttpConnection) Connector.open(your url+";deviceside=true");
if(connection.getResponseCode()==HttpConnection.HTTP_OK) {
write your code, Which you want to get from url or any thing you want
}else{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.inform("connection error");
}
});
}
This may help you :)