I am having an application in android and I want to send the latitude and longitude of the android mobile to the web PHP server through a url (like=..mydata.php?lat=76867&long=87979). I am having the php code that saves the data in database if this url is hit.
All I am not getting is that how to send the latitude and longitude through my android mobile phone to the PHP server.
Building upon #DarkXphenomenon answer, make sure you have the right permissions.
// to retrieve location
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
// to retrieve location
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
// to send data
<uses-permission android:name="android.permission.INTERNET"/>
Then in your java class you can use this code to send the data to the php file. Make sure to catch any exceptions.
String and = "&";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://my site.com/gpsdata.php?imei="+imei+and+"lat="+lat+and+"lng="+lng+and+"alt="+alt+and+"spd="+speed);
try {
httpclient.execute(httppost);
Log.d(TAG, "Data sent!");
} catch (ClientProtocolException e) {
Toast.makeText(this,
"Client protokol exception ", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(this,
"IO exception " + e.getMessage(), Toast.LENGTH_LONG)
.show();
}
You also need to make sure that your location variables such as latitude or longitude are strings otherwise you will get some unexpected errors. Normally the location variables would be a double or a float. To convert a double to a string, excecute
String Longitude = Double.toString(doubleToConvertToString);
And likewise a Float to a String
String Longitude = Float.toString(doubleToConvertToString);
The manifest needs to contain
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />`
Update:
Network connections are no longer allowed in the UI thread. You need to then issue an HTTP get wrapped in an AsyncTask<> which will be parsed and interpreted by your PHP backend.
An example is at http://developer.android.com/training/basics/network-ops/connecting.html
Related
I included following permissions into Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I am using this code:
try {
java.net.URL url = new URL("http://www.temp372.000webhostapp.com/s.php?t=hello_there");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
t1.setText("problem occured..");
}
Following is the PHP code:
<?php
$fn = "android.txt";
$data = "";
// get whatever they send and store it to the file.
if($_GET["t"])
{
$data = $_GET["t"];
if ($data !== '')
{
$myfile = fopen($fn, "a");
fwrite($myfile, $data . "\n");
fclose($myfile);
}
}
?>
No errors are coming, I am trying running this app into bluestacks and my cellphone (ROG Phone).
But results are same, no error or anything as textview is not setting and it just my PHP code is not receiving the information but when I try same URL into my web browser, PHP code runs cool.
HTTP or "clear text" forbidden on default, you should allow it inside < application > in AndroidManifest.xml android:usesCleartextTraffic="true"
It worked well following are things I got:
I don't have to add the following into manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I also didn't have to add any permission like android:usesCleartextTraffic="true" OR any network_security_config.xml in Manifest.
It worked when I ran the code into AsyncTask in Background thread like followings:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
HttpClient httpclient = new DefaultHttpClient();
try {
httpclient.execute(new HttpGet("https://temp372.000webhostapp.com/s_get.php?t=MyWorld"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
I thanks Artem for this and everyone else who were trying their best.
I'm doing some tests using data to register a new user into my DB sending a json by post. The server returns a static string just for testing. I'm getting the proper response using the console and CURL
curl --data '' http://127.0.0.1:3000/api/user/register
<!DOCTYPE html><html><head><title>Express</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>Express</h1><p>Welcome to Express</p></body></html>
and even with the POSTMAN extension sending a post request to that same URL I'm getting a proper response as well. But the code below is not getting any response from the server. What's missing?. It's not throwing any error and the json is correct after checking the debugger(it shouldn't matter but just in case anyone wants to know), just a regular string. The debugger fails on this line
Response response = client.newCall(request).execute();
private void createUser(String name, String email, String password){
//create JSON
final String userJson = formatUserAsJSON(name,email,password);
//send JSON
new AsyncTask<Void,Void,String>(){
#Override
protected String doInBackground(Void... voids) {
try {
//1.create client Object
OkHttpClient client = new OkHttpClient();
//2.Define request being sent to server
RequestBody postData=new FormBody.Builder()
.add("json",userJson)
.build();
Request request=new Request.Builder()
.url("http://127.0.0.1:3000/api/user/register")
.post(postData)
.build();
//3.Transport the request and wait for response to process next
Response response = client.newCall(request).execute();
String result = response.body().string();
return result;
} catch (Exception e) {
Log.d("error_connection","couldn't connect to the API");
return null;
}
}
}.execute();
}
I would appreciate some feedback on this problem. Thank you very much
EDIT: The server is not giving any response cause it's not being reached by the android app. I'm seeing in the ubuntu console and nodejs is not printing any message of any request.....
EDIT 2: In the Android manifest I have the user permission to access the network so it's not that.....
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You are sending your JSON inside a FormBody
try this:
RequestBody postData = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), userJson);
I solved the problem putting the network IP(it also works if you put the Public internet IP, I've tried it) of the server cause 127.0.0.1 was refering to the Genymotion emulator itself, silly me :S. But that was the answer. Thanks everyone for their support.
I'm trying to send a PUT request but failing bad in it.
Only the first time I'm trying to send data the following line follows up in the log (in further use no exceptions are thrown):
E/DataScheduler: isDataSchedulerEnabled():false
I tried to google out what could that possibly mean, but with no luck. And even that in the further attempts on sending data the mentioned exception wont raise anymore, still no data is being sent. I'm trying to send it on my own server and I can see no connections are received on that side. Using my Android's browser I can send a successful GET request however.
I've also set the permission for Internet already by:
<uses-permission android:name="android.permission.INTERNET" />
I'm not very familiar with Java or Android but as far as I know the request should be formed and sent the following way:
public void sendFilesWithPut(String address, String file) {
new AsyncTask<String,Void,Void>() {
#Override
protected Void doInBackground(String... params) {
try {
//Log.d("HTTP:","Address:"+params[0]+":"+params[1]+" file:"+params[2]);
URL url = new URL("http://" + params[0] + ":" + params[1]);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
out.write(params[2]);
out.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute(address, Integer.toString(port), file);
}
I can print a line to Log every time I attempt to send a PUT request and it's all correct: IP, port and the to-be-sent-String.
Any ideas how to make it work?
I suspect that params[0] and params[1] are actually the address and port for your url. If so then you may wish to refer to the following post:
Making PUT request with JSON data using HttpURLConnection is not working
Where the content will be sent if you start interaction with the response, so add the following:
System.err.println(httpCon.getResponseCode());
as per the post, and see if that works?
I am trying to do a http post to my server to check if the login credentials are valid with help of this tutorial. I need to make a request to my server but i have to add Authorization, i get the string with the function getB64Auth from this answer. the function logs the right variable, (the same as i use with postman). But for some reason my program stops running if i run my code. I already tried adding the code from the comments but it didn't help.
What am i doing wrong?
private String getB64Auth (String login, String pass) {
String source=login+":"+pass;
String ret="Basic "+Base64.encodeToString(source.getBytes(),Base64.URL_SAFE| Base64.NO_WRAP);
Log.d("authy", ret);
return ret;
}
/** Called when the user clicks the Login button */
public void login(View view) {
// Getting username and password
EditText userText = (EditText) findViewById(R.id.inputLoginUsername);
EditText passText = (EditText) findViewById(R.id.inputLoginPassword);
String usernameInput = userText.getText().toString();
String passwordInput = passText.getText().toString();
String authorizationString = getB64Auth(usernameInput,passwordInput );
// Do something in response to button
// 1. Create an object of HttpClient
HttpClient httpClient = new DefaultHttpClient();
// 2. Create an object of HttpPost
// I have my real server name down here
HttpPost httpPost = new HttpPost("https://myservername.com/login");
// 3. Add POST parameters
httpPost.setHeader("Authorization", authorizationString);
// 5. Finally making an HTTP POST request
try {
HttpResponse response = httpClient.execute(httpPost);
Log.d("win", "win1");
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
Log.d("fail", "Fail 3");
// Log exception
e.printStackTrace();
} catch (IOException e) {
Log.d("fail", "Fail 4");
// Log exception
e.printStackTrace();
}
}
When i run my code the app stops working, i can find the log authy but i cant find any fail succes logs.
The things i have changed in the example are step 3.
ive added my authorization there.
and removed step 4 cause i dont need it.
Working postman example, with the same request i want to make in android.
You can see I get a response, and only set Authorization on my request.
I cant find any decent post/authorization tutorials so i hope i'm looking at the right direction.
It's an android 4.* project
Just a few suggestions about such issues:
Check permissions (INTERNET is the one you would need)
Applications like Charles / Fiddler let you sniff the Http traffic from the device so you could investigate what is being sent
If the application is crashing - check the LogCat messages (for example it could contain a message explaining which permission is missing)
Regarding this message:
The application may be doing too much work on its main thread.
This usually means that you are doing some heavy operations in the main thread - for example parsing the Json from the Http response. Generally you'd like to do all these operations in a background thread and use the main one to update the UI only.
In my app i have access to web server. It works fine in Some phones but while testing in Samsung Galaxy
Model No - GT-S5830i
Android Version - 2.3.6
it keeps on showing Unknown host exception. I have checked the url from browser its working fine.
private void submitUploadData(String url ,Map<String, String> param) throws IOException
{
URL siteUrl;
try {
siteUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
Set getkey = param.keySet();
Iterator keyIter = getkey.iterator();
String content = "";
for(int i=0; keyIter.hasNext(); i++) {
Object key = keyIter.next();
if(i!=0) {
content += "&";
}
content += key + "=" + param.get(key);
}
out.writeBytes(content.trim());
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while((line=in.readLine())!=null) {
System.out.println(line);
}
in.close();
//Intent home = new Intent(SyncHttp.this,TimeAndExpensesSKActivity.class);
//startActivity(home);
db.updateTimeExported(1);
db.updateExpensesExported(1);
db.close();
db.close();
if(db.getLogCount()==0){
db.insertSyncDateDetails(getDateandTime());}
else{
db.updateSyncDateDetails(1, getDateandTime());}
} catch (MalformedURLException e) {
e.printStackTrace();
}
this.setResult(FINISH_RESULT);
db.close();
}
I have already added permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
I am really confused why this exception occurring.
Thanks for your help guys.
My app did this too. This usually caused by unstable network connection. What I did was catching this UnknownHostException and modify the code in a way that if UnknownHostException happened, I try to re-fetch the URL again, after several miliseconds sleep.
The basic algorithm is something like this:
private void submitUploadData(String url ,Map<String, String> param) throws IOException
{
URL siteUrl;
boolean isDataSubmitted = false;
while(!isDataSubmitted){
try {
//do your complicated http process
isDataSubmitted = true;
} catch(UnknownHostException uhe){
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
I have also experienced some issues using URLConnections especially HTTPS on the Samsung Galaxy TAB, but i would imagine it probably occurs on other models as well since there are a ton of devices with the same name but made for different markets and mobile providers.
So far i haven't found a way around sorry, since i tend to avoid the URLConnection class due to a ton of other issues it has.
I suggest using the Apache HTTP Client to communicate with your API's. you can google a ton of examples of using it.
Also when looking at your code i would suggest reading a bit more into the try-catch-finally block statements in java. it is really important to properly close connections at the end or in case of errors.
Other possibilities are:
There is no connection of any sort active (mobile or wifi)
You are missing the "http://www." in your url.
I think calling close() on the DataOutputStream before you recieve your input might close the whole connection - try commenting out that line.
Have you checked the URL from the phone's browser?
Please log the URL you pass to the function and try it in your phone's browser. I would think of missing/incorrect protocol specifier and or URL string formation issues of which this particular phone is unforgiving.