Reputation: 58
I am working on an android app that needs to connect to localhost which is on another computer in the same network. I have no problems connecting to the localhost through another computer but how do i connect to the localhost through android? I am using android studio and have created the database using MySql and php scripts through wamp.
Upvotes: 0
Views: 2737
Reputation: 58
Thank you everyone for answering. In the end I used Android Volley, it is another library. You can google for the tutorial.
Thank you Rafique Mohammed
Documentation - http://developer.android.com/training/volley/index.html
Upvotes: 1
Reputation: 1309
"localhost" address always only points to the device you are calling it from.
Example: If you call/navigate to "localhost" from your wamp computer, it will return the content served from your computer. If you do the same on your android device, it will return you the content served from your android device.
From what I understand from your question is that you would like to access your wamp server from an app on your android device. To do so, you should make your network requests from your android app to the ip address of your computer (not to "localhost"), that is running a wamp server. You can get the ip of your computer by calling "ipconfig" in cmd (windows) or "ifconfig" in terminal (linux).
In your app you should use Http(s)URLConnection and you need to use it in a non UI thread so it wont crash your app. You can use AsyncTask for that.
Here is a sample code for this:
public class DBqueryS extends AsyncTask<String,String,String>{
final Handler mHandler;
private static String urlLink = "";
public DBqueryS(Handler handler) {
urlLink = "YOUR_SERVER_ADDRESS";
mHandler = handler; //Handler from UI activity that will receive the request response when it arrives
Log.i("DBquery", "" + action);
}
@Override
protected String doInBackground(String... strings) {
//get execution parameters from strings
return postText();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//Do something before "doInBackground()"
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Do something after "doInBackground()"
mHandler.obtainMessage(HTTP_REQUEST_COMPLETE,s).sendToTarget();
}
private String postText(){
try{
// add request data
List<NameValuePair> nameValuePairs = new ArrayList<>(0);
nameValuePairs.add(new BasicNameValuePair("key",value));
Log.i("DBquery sent", nameValuePairs.toString());
// HttpClient
URL url = new URL(urlLink);
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setReadTimeout(5000 /* milliseconds */);
connection.setConnectTimeout(3000 /* milliseconds */);
connection.setRequestMethod("POST"); //Can be GET,...
connection.setDoInput(true);
connection.setDoOutput(true);
// attach data
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
writer.write(getQuery(nameValuePairs));
writer.flush();
writer.close();
os.close();
// execute HTTP post request
connection.connect();
// read response
int responseCode = connection.getResponseCode();
Log.i("DBqueryS", "Https response is: " + responseCode);
InputStream is = null;
is = connection.getInputStream();
String responseStr = readIt(is, 1);
if (responseStr != null) {
return responseStr;
}else{
Log.i("HTTP RESPONSE","NO RESPONSE");
}
} catch (ClientProtocolException e) {
Log.e("CONN_EXCEPTION", e.toString());
} catch (IOException e) {
Log.e("CONN_EXCEPTION",e.toString());
}
return "FAILED";
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException {
String str = "";
Reader reader;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
while(reader.read(buffer) > 0){
str+=String.valueOf(buffer);
}
Log.i("DBqueryS", "Read " + str.length() + " characters.");
if(str.length()>0)return str;
return null;
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
}
For more info on HttpsURLConnection and AsyncTask refer to these pages: http://developer.android.com/reference/javax/net/ssl/HttpsURLConnection.html
http://developer.android.com/reference/android/os/AsyncTask.html
Upvotes: 0
Reputation: 523
You have to put your server in the network. After that you can access with the IpAdress of your computer. I never did this with Wamp server.
How to enable local network users to access my WAMP sites?
To connect your Android mobile you can use HttpUrlConnection : http://developer.android.com/reference/java/net/HttpURLConnection.html
If you want to show your WebPage you can use WebView : http://developer.android.com/reference/android/webkit/WebView.html
Here is my class to connect to a server. I put in the constructor a Listner. The listener is a Class who implements an interface. With that you can Override the mehtod of interface and when the asyn task finish (listner.onTaskCompleted in the onPostExecute) the methode is call.
package controller;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by mwissle on 26/02/2016.
* Class permettant de récupérer le JSON depuis internet
*/
public class YourClassForConnection extends AsyncTask<String, String, String> {
private AsyncResponse listener;
HttpURLConnection conn = null; //New object HttpURLConnection
public YourClassForConnection(AsyncResponse listener){
this.listener=listener;
}
protected void onPreExecute() {
progress = new ProgressDialog(activity);
}
@Override
protected String doInBackground(String... params) {
String response = "";
String responseError = "";
try{
//Connect to URL
Log.d("JSON", "Start of connexion");
URL url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.connect();
int responseCode=conn.getResponseCode();
//HTTP_OK --> 200
//HTTP_CONFLICT --> 409
if (responseCode == HttpsURLConnection.HTTP_OK ) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
return response;
}
else if(responseCode == HttpURLConnection.HTTP_CONFLICT){
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getErrorStream()));
while ((line=br.readLine()) != null) {
responseError+=line;
}
return responseError;
}
else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null){
conn.disconnect();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
try{
super.onPostExecute(result);
listener.onTaskCompleted(result);
}
catch(NullPointerException npe){
Log.d("NullPointerException", npe.getMessage());
}
}
}
Upvotes: 0