I am trying to connect to the server from android through tomcat server. There is a .class file which should be eecuted. I have placed this in C:/xampp/tomcat/webapps/examples/WEB-INF/classes/LoginServlet.java
to access this from android, I have given the statement,
response = SimpleHttpClient.executeHttpPost("http://10.0.2.2:8080/webapps/examples/WEB- INF/classes/LoginServlet", postParameters);
Is that corrext? Do I have to place it in a different location or change the path above ?
Related
I am trying to connect Flutter's HttpClient to fetch data from my local server which is running on ASP.Net Core 3.0. The problem is I get the Error 400(Bad Request) each time I try.
Here's the flutter code:
String token = await SharedPreferencesService.getStringFromSF('idToken');
var client = new HttpClient();
client.badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
HttpClientRequest request =
await client.getUrl(Uri.parse('https://10.0.2.2:44383/weatherforcast'));
request.headers.add('idToken', token);
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
The asp.net core 3.0 endpoint:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public User Get()
{
return new User { UserId = 1332, Username = "Michal" };
}
}
The Error
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Hostname</h2>
<hr><p>HTTP Error 400. The request hostname is invalid.</p>
I can confirm that I get the data in the browser as well as on postman.
Thank you for the help.
Okay, I fixed the issue by a debugging it step by step.
It seems like the Android doesn't like the self-signed certificates, thus I couldn't really set it up to use HTTPS in the end.
What I did though is I made it work with sole HTTP and these are the steps:
Change IIS to your local runtime environment (by default the name of the project)
Delete app.UseHttpsRedirection(); in the server Configuration method
We now enabled HTTP requests to our server. What comes next is running the server through our local runtime environment (which we can change in a Debug button in VS).
Now, we should be able to access the api in our browser in the Android Emulator using an http request e.g. http://localhost:5000/weatherforcast.
Remember that ASP.NET Core 3.0 by default serves the HTTPS on port 5001 and HTTP on 5000.
Next, Android uses an alias for the IP of the local machine the server is running, so instead of writing localhost:<port> we have to write 10.0.2.2:<port>
Lastly, I simplified the api call in the client to look like this:
static Future<Profile> getUserProfile() async {
String url = 'http://10.0.2.2:5000/weatherforecast';
final reply = await http.get('$url');
var responseJson = json.decode(reply.body);
return Profile.fromJson(responseJson);
}
To solve this problem first we need to understand the way Android Emulator works:
First tip you should understand is that the Android emulator (a
virtual device) has its own networking. So Google defines a magic IP
address “10.0.2.2”. If you try to browse to this IP address, the
requests would be routed to “127.0.0.1” loopback adapter of the host
machine. (Later I will give you proof on the magic routing.)
It's simple: if you put localhost on the adress it will hit the own android emulator network. So if we put 10.0.0.2, that is converted to 127.0.0.1, and we are able to acess our machine network.
The problem is that IIS doesn't have a binding for https requests on 127.0.0.1:port address, just for localhost:port. Try yourself: run your .NET Core API, go to the browser and type in 127.0.0.1:port. You'll receive the 400 - Bad Request error right in your face.
So, how to make the IIS recognize the 127.0.0.1:port address?
You'll have to mess up with the ISS Express config file and add the binding manually. Follow the steps:
1 - Open your applicationHost.config project file. In VS2019, it is inside $(solutionDir)\.vs\{projectName}\config\applicationhost.config.
The .vs folder is hidden, so make sure to tell your file explorer to show hidden directories.
For other Visual Studio versions, look this link: Where is the IIS Express configuration / metabase file found?
2 - CRTL + F to search for port:localhost and you'll find the binding lines that are already configured for your project.
3 - Insert a line for the https protocol and the 127.0.0.1:port adress. Your bindings now should look like this:
<bindings>
<binding protocol="https" bindingInformation="*:port:localhost" />
<binding protocol="https" bindingInformation="*:port:127.0.0.1" /> <!-- here is your line -->
<binding protocol="http" bindingInformation="*:otherPort:localhost" />
</bindings>
Now, go back to your browser and try to reach 127.0.0.1:port. You should make it without any errors. So does your Flutter application. Enjoy!
References: How to let android emulator acess IIS Express? - Lexstudio
Really useful.
Just one thing, I got stuck where you should
What comes next is running the server through our local runtime environment (which we can change in a Debug button in VS).
To do this:
Open the project properties and set the App URL to only http
Hello I am building my first android app, I am currently trying to post data to a URL on my local server. When I try with my live server it works however with my local server it does not, nothing happens at all, I get no response.
This is the route in my app on my localhost: http://admin.website.dev
I changed my hosts file and virtual host configuration on my localhost so that any address with the extension ".dev" points to a folder on my localhost. eg. "localhost/website"
Is there a reason this does not work in my android app when I try posting data?
I have already added the INTERNET permission in my manifest file.
Since android 5, you need to make a POST on DNS valid URL.
I'm not sure if your changes on hosts file will work.
I was wondering if it was possible to download a file without giving the specific file URL.
For instance, making an http request and inside the response were the file or the content of the file.
I'm able to download a file already giving the exact URL.
For instance, txt file.
But, what I want next is to protect that URL and make it private.
If there is another way, then please explain me
There is a way to facilitate server-client communication without using http request, referred to as Apache Thrift. To achieve the goal you asked - "Download a file from server without giving the file URL", you can do as follow:
Download Thrift, Build and Install Apache Thrift compiler
You can follow steps on official website.
Writing a .thrift file (For my example, I named it as "test.thrift")
For your example, you can define as below:
service MyServer {
binary getFileFromServer()
}
Then, open you terminal and run
thrift --gen java test.thrift
I'll get a "MyServer.java" file and both server/client sides should include this file for implementing. Assuming your server side is prepared for providing file data as binary. In your Android app, you just need to specify the socket, protocol, transport, host, and port for connecting server. And if you would like to get file from server, just using your Client object to call "getFileFromServer()", then you can get the byte[] of your file. For instance:
public TSocket socket = new TSocket(your_host, your_port);
public TFramedTransport transport = new TFramedTransport(socket);
public TBinaryProtocol protocol = new TBinaryProtocol(transport);
public Client myClient = new Client(protocol);
call a thread to get file from server:
new Thread(new Runnable() {
#Override
public void run(){
// this block should be wrapped with try/catch
transport.open();
byte[] myFileInByteArray = myClient.getFileFromServer();
// your custom function for decoding
decodeByteArrayIntoFile(myFileInByteArray);
transport.close();
}
}).start();
The above is the only way I can think of to download a file from server without giving the file URL, but your still need to connect to your server first. Hope this can help.
I am using an embedded http server from the following example on
https://github.com/nikkiii/embedhttp
The http server code is initiated as
File filesDir = getFilesDir();
HttpServer server = new HttpServer();
server.addRequestHandler(new HttpStaticFileHandler(new File(".")));
server.addRequestHandler(new HttpStaticFileHandler(filesDir));
server.bind(8081);
// Start the server thread
server.start();
The http server is embedded so as to serve a www folder from the server as http://localhost:8081/folderpath/index.html . Then in turn I will be using WebView to access the localhost url.
In webview I try to access.
myWebView.loadUrl("`http://localhost:8081/`");
myWebView.loadUrl("`http://localhost:8081/index.html`");
myWebView.loadUrl("`http://localhost:8081/www/index.html`");
myWebView.loadUrl("`http://localhost:8081/assets/www/index.html`");
But none of them work. What is the probable solution to such a situation where the assets/www flder needs to be served from localhost running on android. Thanks.
The Android assets folder is not available via getFilesDir(): getFilesDir() returns a different directory. To serve resources in the assets folder you'll need to use AssetManager (http://developer.android.com/reference/android/content/res/AssetManager.html) and do a little translation from your request paths to the appropriate resource.
If I want to access folders that are uploaded on a server, how would I access it from the Android project? I tried to use the following
public URL(String protocol, String host, String file)
My Codes:
URL url = new URL("file", "www.websitename.com", "/folderX");
MyClassName path = new MyClassName(url);
Seems like it couldn't access the folder on the server still. Is there anything that I miss or I should be using some other ways? There are no errors in the logcat so I am not sure what is it. No MalformedURLException being thrown as well.
I you want to access the folder and its files from your server you need FTP account details to connect to your server from your android device.There are more FTP Client libraries available to access the files one of them is
http://commons.apache.org/net/download_net.cgi