How to change file capabilities on Android? [duplicate] - android

Is it possible to host a web server within an Android phone itself?
Similar to Apache. I want to access the web server from the mobile
browser itself.
Couldn't find any reference online. Is this possible?
Thanks in advance

Short: yes. If you are looking at code, check out the org.apache.http package. If you are looking at a ready app, check iJetty and kWS.

KSWEB — a suite for web development on the Android platform. It consists of: a web server, PHP programming language and the database MySQL. KSWEB allows you to organize a platform for running and debugging Web applications (sites) in your Android device. Working with the application is very simple. To start the server it is enough to run our application, select, if necessary, port and the root directory.
By default, KSWEB contains a fully functional configuration file of the server, PHP and MySQL. However, if you want something to change them, go to the server options and click on the item «INI Files». Configuration files will be moved to SD-card of your device at «/mnt/sdcard/ksweb/ini/», if available. If repeatedly clicking on the item settings «INI Files» KSWEB will use the internal configuration files.
What's in the plans?
Review the requirements for the Android operating system, in particular
reduce the requirements for the version of Android to run the application to 2.0;
Add the ability to track the flow of errors arising when working with php and mysql;
Move the log files on the server and mysql on sdcard;
Extend the additional PHP libraries. For example, pdo_mysql;
Move the database files to MySQL on sdcard.
https://play.google.com/store/apps/details?id=ru.kslabs.ksweb
http://www.kswebserver.ru/

Atjeews android app server, small footprint, biggest advantage for me was jsp support.

I recently installed BitWeb which I recommend highly. I have a rooted phone with lends me a few more options (and I also recommend rooting if you haven't and plan on doing any server tinkering at all)
BitWeb is nice in that it includes a lighttpd server, a stripped down php engine and a stripped down mysql engine giving you a quick and dirty LAMP system with just one app. I use mine in conjunction with an sshd app to gain a busybox shell, I installed nano and use the ssh connection to do an sshfs share to edit content from my pc.
Bitweb includes the ability to tweak the config settings for all three services, and I've even managed to get multiple Zend servers working on just the one little server with a little tweaking to the re-write rules and the application.ini settings.
https://play.google.com/store/apps/details?id=com.andi.serverweb&hl=en
If you want to see some of the config options I had to customize, I can either post them or respond via email with what I set up as well as some comments on the pitfalls I ran into along the way. (I recently posted one as a self-answered thread on here by the way, although it turned out not to be specific to the android platform but with lighttpd/Zend)
I'm just bummed that t-mobile/HTC appears to have no plans to upgrade my phone beyond Gingerbread as I understand some of the new android OS's have ways you can access some of the hardware (such as the cameras) from scripts or compiled code without a fuss. If I want to do it now, I either need to hard code my own interface to them or get a pre-roll app capable of doing it which really tasks my phone when running side-by-side with the web/mysql/php services.

I might be a last to answer this question but believe me, this is the simplest and latest answer in 2020 for those who need to start a webserver in Android and need to serve multiple clients without implementing any other third-party libraries.
Copy your HTML file into the assets folder of Android as server.html and declare the serverSocket as global in your class.
Run the below code inside a new thread.
try {
serverSocket = new ServerSocket(8080);
while (true) {
final Socket socket = serverSocket.accept();
new Thread(new Runnable() {
#Override
public void run() {
try {
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter os = new PrintWriter(socket.getOutputStream(), true);
String request = is.readLine();
Scanner scanner = new Scanner(getAssets().open("server.html"));
String response = scanner.useDelimiter("\\Z").next();
os.print("HTTP/1.0 200" + "\r\n");
os.print("Content type: text/html" + "\r\n");
os.print("Content length: " + response.length() + "\r\n");
os.print("\r\n");
os.print(response + "\r\n");
os.flush();
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}).start();
}
} catch (Exception ex) {
ex.printStackTrace();
}
That's all your native Android Java (no third-party libraries implemented) webserver is live at port 8080.
If you want to use DB and POST requests, try to implement SQLite and WebSocket connections to make two-way communication.
https://developer.android.com/reference/java/net/ServerSocket

Check KSWEB and Bit Web Server,
both using Lighttpd als server, php and support mysql.
i tried KSWEB, it works wonderfull, but i don't know yet how to use the modrewrite.
but, it should be work. you can try the trial version of KSWEB before purchase it.
KSWEB costs a little bit more than Bit Web Server only 0,XX $.
if you decided to buy it, post your experience here... i want to know too... :)
Bit Web Server
KSWEB

Till now I have seen all those applications are paid . And others doesn't have phpmyadmin. And I found finally one. You can have a look at kickweb server.
Android web server PHP/MySQL/PHPMyAdmin
Requirements
Internal memory should not be less than 50MB!
Minimum Android API 9 (GINGERBREAD)!
Features
Lighttpd 1.4.34
PHP 5.5.9
MySQL 5.1.62
MSMTP 1.4.31
phpMyAdmin 4.1.10
Nginx 1.5.11
Default Document Root (htdocs)
Path : /sdcard/htdocs/
Default URL
Address : localhost:8080
phpMyAdmin Informations
Address : localhost:10000
Username : root
Password :
MySQL Informations
Host : localhost
Port : 3306
Username : root
Password :
If you find trouble to make it working, you can see this video : https://youtu.be/3_m3vNGTp74

Yes, it is possible. May be not so complicated as Apache, but possible.
Look at Moto Phone Portal for example, it has web-server in its base. And there were several applications for this purpose in Market.

Servers Ultimate Pro, just 8 pounds.
Include PHPAdmin, MySQL and ton of other servers. I am currently using it as proxy.

Related

MAUI Blazor App can't connect to MongoDB Atlas via ConnectionString, why?

I coded a MAUI Blazor App which connects to MongoDB Atlas and loads some Data in the App. Everything works fine if I run the App on a Windows PC. But if I compile/run the same code on an Android device I get this error in the development tools:
**blazor.webview.js:1 List of configured name servers must not be empty. (Parameter 'servers')**
at DnsClient.LookupClient.QueryInternal(DnsQuestion question, DnsQuerySettings queryOptions, IReadOnlyCollection`1 servers)
at DnsClient.LookupClient.Query(DnsQuestion question)
at DnsClient.LookupClient.Query(String query, QueryType queryType, QueryClass queryClass)
at MongoDB.Driver.Core.Misc.DnsClientWrapper.ResolveTxtRecords(String domainName, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Configuration.ConnectionString.Resolve(Boolean resolveHosts, CancellationToken cancellationToken)
at MongoDB.Driver.MongoUrl.Resolve(Boolean resolveHosts, CancellationToken cancellationToken)
at MongoDB.Driver.MongoClientSettings.FromUrl(MongoUrl url)
at MongoDB.Driver.MongoClientSettings.FromConnectionString(String connectionString)
at MongoDB.Driver.MongoClient..ctor(String connectionString)
at MBz_MauiAndMongoDb.Pages.Index.OnInitializedAsync() in **C:\Users\XXX\source\repos\MBz_MauiAndMongoDb\MBz_MauiAndMongoDb\Pages\Index.razor:line 23
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()**
The error occures at is moment:
var client = new MongoClient(MongoDbConnectionString);
var db = client.GetDatabase(MongoDbName);
The ConnectionString works perfect if run on a Windows maschine. The ConnectionString looks like this:
"mongodb+srv://AtlasUser: myUserName+myCluster/test?retryWrites=true&w=majority&ssl=true"
I use the MongoDB.Bson and the C# MongoDB.Driver.
In the Documentations I only find the connectionString Syntax I use. But that seems to NOT work with MAUI App on a Android-Device! If I just use "mongodb://AtlasUser:..." without the 'srv' I get a timeout error. Or is it a problem with permissions under Android, I didn't change the original MAUI Blazor template stuff in that regard. Any Ideas?
Thx for your Help!
It's simple: on WebAssembly you cannot do something impossible to do using JavaScript in a browser.
The mongodb:// protocol is a TCP based protocol and cannot be connected from any kind of code running in a browser. This limitation is not specific to Blazor.. any other WebAssembly like Uno Platform will have the exact same limitations.
You have 2 options to circumvent this:
You connect to a server part of your application using http/https (it could be REST API, WebSockets, SignalR or whatever else running on http) and, from there, you connect to the MongoDB server.
You connect directly to the MongoDB server using a REST interface -- but I'm pretty sure the MongoDB.Driver won't be able to use them and you'll have to build your queries by yourself.
Disclamer: I'm a senior architect at Uno Platform working on the WebAssembly platform.
This answere from the MongoDB Forum solved my problem:
Welcome back to the MongoDB Community Forums. I see that you’re having problems running a MAUI Blazor app using the MongoDB .NET/C# Driver. The error you’ve encountered is coming from one of our third-party dependencies, DnsClient.NET, which we use for SRV and TXT DNS lookups. The error indicates that autodiscovery of nameservers wasn’t successful. You can read more about it in DnsClient.NET issue #143.
While in theory you could manually configure DNS nameservers when instantiating the LookupClient instance, our driver does not expose the ability to supply arguments to the LookupClient constructor.
Two options:
Figure out why DnsClient.NET cannot autodiscover the configured DNS nameservers.
Use the standard connection string format (e.g. mongodb://) instead of the DNS seed list connection format (e.g. mongodb+srv://).
The latter option works because we only use DnsClient.NET for SRV and TXT lookups. A, AAAA, CNAME, and other DNS records are performed automatically by the operating system. Note that simply removing +srv from the connection string is not sufficient. The hostnames are different. If you’re using MongoDB Atlas, go to your cluster page, select Connect, Connect your application, C# / .NET 2.4 or later, and you should see a connection string that looks like:
mongodb://<username>:<password>#cluster0-shard-00-00.CLUSTER_NAME.mongodb.net:27017,cluster0-shard-00-01.CLUSTER_NAME.mongodb.net:27017,cluster0-shard-00-02.CLUSTER_NAME.mongodb.net:27017/?ssl=true&replicaSet=REPLSET_NAME&authSource=admin&retryWrites=true&w=majority

I can't access my Apache server from my Android device

it is my second time asking a question on stackoverflow. I'm trying to access to my local apache server that I've set up on my desktop computer (ip that starts with ie. 192.168.1*.**)on my android phone. but somehow it does not allow me to access to the server at all! :( strangely, sometimes it does allow me to access to the server lol! but it's only one out of 20 for each attempts. Also, it doesn't allow me to access to the server on my laptop either.. I really need some help guys.. it was working fine when i was working locally within my desktop pc by using emulator. I've done quite a lot of research about it but i wasn't able to find any solutions.
Thank you guys
=====================================
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient client = new DefaultHttpClient(setHttpParams());
HttpPost request = new HttpPost(PATH + FILENAME);
if (json != null) {
request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
request.setHeader("json", json.toString());
} else {
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
HttpResponse response = client.execute(request);
so that is the code, error occurs when it tries to execute the request. request includes the apache server ip PATH (192.168.**) + FILE_NAME(ie. index.php). I know why it causes the error because i cannot access to the 192.168.* server and read the desired file. I need help with this =(
For the computer running the webserver:
Make sure that your personal firewall rules are not preventing access to the web server.
For your phone to access the webserver over the air the server needs to be accessible from the web. It could be that your machine is behind a corporate firewall which is preventing access to it from external sources.
If you simply want to access it from the phone, make sure that both the webserver and phone are on the same network i.e. they have IP addresses from the same address range. You can do that by connecting your machine to wireless AP (either via ethernet or wireless) and making sure that your phone is connected to the same wireless AP.
Moreover I just read your question again and noticed the line
it does not allow access to to the server on my laptop either
If you cannot access the webserver locally on the machine it is runnning on then there is something wrong in the way you configured your web server.
So first make sure that your web server is running and configured properly. Open a browser and go to http://localhost or http://192.168.x.x if everything is configured right you will be able to access your web pages.
Basically this is networking 101, if it is still giving you problem post some details such as what webserver, what port etc.
If you are new to networking concepts and don't know how to configure a web server say Apache just Google how to configure Apache or use something called XAMPP which is a developer friendly bundle containing Apache, MySQL, PHP, FileZilla etc. Note that XAMPP shall never be used in a production environment as its default configuration is done in a way to make it easier to install, configure and run above mentioned packages for new users.

Set android system wide proxy settings

I am looking into writing an Android tablet app as part of a wide parental control solution.
The app should set the tablet to work with a proxy server that will be used system wide (all apps on that device will be forced to go thought the proxy server).
The proxy server job will be to filter and monitor all outgoing connections from the tablet. As part of that, only specific sites will be available while most of the apps will be blocked (including the Google play store or any other communication app installed on the device).
As an extra, I want the user to not be able to change or remove the proxy settings if it's by monitoring and changing the settings back or by blocking the user with a password.
The actual proxy server is already running and functional.
It is important the app will not require a custom ROM and/or root access
Can it be done?
By default the control app wont work without having access to the all system - means a root access- You can try to understand the principle used by Android Anti Virus software and that will help more.
By default as if now it is not possible to set Proxy for Apps ...
I had the same problem for a while. I use a library that does http requests, but I can't acces the source. So I started digging and there were two things that I needed to do. One was to add this piece of code before my own http requests:
HttpClient httpClient = new DefaultHttpClient();
if (useProxy) {
HttpHost proxy = new HttpHost("192.168.1.10", 8080, "http");
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
//use httpClient for a request here
But this did not solve my problem entirely. I couldn't access the source of the library that made it's own requests. I looked for more solutions and I found that you can use the following code to set a default proxy for all requests that your app makes.
System.setProperty("http.proxyHost", "192.168.1.10");
System.setProperty("http.proxyPort", "8080");
After adding this code, the requests from the library go through the proxy as well.

Streaming bytes from controller, android browser, download fails

Grails 1.3.7
I have some code that looks like this...
response.setHeader("Content-disposition", "attachment; filename=${fileName}")
response.contentType = download.contentType
response.contentLength = file.length()
response.outputStream << file.getBytes()
On the desktop and on the iPad, the downloads work just fine. But on android devices it just gives me "Unknown myserver.com In progress". And then eventually fails. A couple of points...
This happens locally, staging, and on production servers
Testing without SSL, everything works fine.
When I try the download in the Dolphin Browser I get the same results
with an added bit of text "Waiting for data connection"
Update #2: Stacktrace that only occurs when downloading from an Android device:
Stacktrace follows:
java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at com.sun.net.ssl.internal.ssl.OutputRecord.writeBuffer(OutputRecord.java:297)
at com.sun.net.ssl.internal.ssl.OutputRecord.write(OutputRecord.java:286)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecordInternal(SSLSocketImpl.java:743)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:731)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:59)
at com.wbr.consumer.ProductController$_closure1_closure2.doCall(ProductController.groovy:30)
at com.wbr.consumer.ProductController$_closure1.doCall(ProductController.groovy:28)
at com.wbr.consumer.ProductController$_closure1.doCall(ProductController.groovy)
at java.lang.Thread.run(Thread.java:680)
I realize this is a few months late but I also ran into this issue with the Android browser and a Grails application I was working on.
The issue appears to be how Android handles downloadable content and the android browser integration with download manager.
http://code.google.com/p/android/issues/detail?id=1978
http://code.google.com/p/android/issues/detail?id=18462
I was receiving two requests on the server side for a downloadable file; one from the browser and one from the download manager. The one from the browser ends up getting terminated and the socket closed as soon as the browser determines that it is downloadable content. The browser then hands off the download to the download manager.
I was also having issues with the download failing from download manager but that had to due with me not sending headers as soon as they were ready. I ran into this only with larger APKs, small APKs (under 10-20K) seemed to download just fine.
Some code may help:
response.contentType = 'application/vnd.android.package-archive'
response.addHeader('Content-Disposition', 'attachment; filename=FILENAME.APK')
// output file content
response.setStatus(200)
response.setContentLength("CONTENTSIZE")
// send headers
response.flushBuffer()
try {
response.outputStream << {FILE}.getBytes()
response.outputStream.flush()
} catch (SocketException e) {
log.error(e)
}
return
With this, I always end up with one socket exception. Don't know if thats avoidable, from some quick searching I didn't see a way to determine socket state from servlet without simply trying to write to the socket.
It sounds like there are potentially 2 issues
the browser you are using does not trust the self signed cert.
Do other SSL sites work from this browser?
Can you install your STG
cert into the browser's trusted certs store?
A stupid question is : did you get the request URL correct? https vs http ... i know it's stupid.....
the response is never flushed to the client. Try this:
response.outputStream.flush()

How to debug http calls on Android devices?

I'm writing a Lovefilm client for Android, and it's not going too badly except I keep having problems with the remote calls to retrieve data from the API.
Does anyone have any tips for debugging remote calls like this? Can I tcpdump on Android or is there a native way of doing it?
For example, I'm using the Scribe-java library for OAuth to access the Lovefilm API, I can authenticate find and retrieve a list of films on the users account fine when the device is running Gingerbread, but trying to retrieve the accessToken on Froyo causes a blank response & and apparent response code of -1, I'd like to be able to see what's going on under the cvers their.
Another example I'd like to be able to the raw http for is trying to run a search, I get and IOError that says "Received authentication challenge is null"
I've used Fiddler (http-proxy for debugging http calls) with the android emulator in these cases. Just start the proxy, and start the emulator with the correct proxy address (-http-proxy ).
Fiddler is the most useful option. On the emulator #Scythe answer will work, but on a real device you will need to set the proxy in the Apache Http Client. The following code will do that:
HttpHost proxy = new HttpHost("youripaddr", 8888);
params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
If you are using https, fiddler is not so useful. In that case can enable the build in logging support in Apache Http Client. The following code does that:
Headers only:
java.util.logging.Logger apacheHeaderLog = java.util.logging.Logger.getLogger("org.apache.http.headers");
apacheHeaderLog.setLevel(java.util.logging.Level.FINEST);
Headers & Wire:
java.util.logging.Logger apacheWireLog = java.util.logging.Logger.getLogger("org.apache.http.wire");
apacheWireLog.setLevel(java.util.logging.Level.FINEST);
Note that this will have to have a java.util.logging Handler configured at finest level and the default handler is configured to log to logcat, which will filter DEBUG (finest) entries by default.
If your system can share the wi-fi connection you should be able to route packets from any device through your system and then using wireshark you can get monitor your calls or get a tcpdump.
Also , and more importantly , it would be best if you log your network calls and responses as suggested by #Matthew
Windows 7 wi-fi connection sharing : http://www.winsupersite.com/article/faqtip/windows-7-tip-of-the-week-use-wireless-hosted-networking-to-share-an-internet-connection-wirelessly.aspx
Since I always run into similar troubles and it seems a lot of people having the same issues over and over again I wrote up a quick tutorial for debugging client-server communication by using netcat and cURL.
That of course only works for the simplified case that you always 'fake' on side of the connection.
For eavesdropping you can use tools like tcpdump or Wireshark. Which will definitely be easier if you're able to run the server instance directly on your local machine.
Stetho is a great tool from FB which helps in debugging android Apps. You can have access to local data and have a check on your network using this.
http://facebook.github.io/stetho/

Categories

Resources