我正在开发一个需要连接到同一网络中另一台计算机上的localhost的Android应用程序。我通过另一台计算机连接到localhost没有问题,但我如何通过android连接到localhost?我正在使用android studio,并通过wamp使用MySql和php脚本创建了数据库。
答案 0 :(得分:1)
谢谢大家的回答。最后我使用的是Android Volley,它是另一个库。你可以谷歌搜索教程。
谢谢Rafique Mohammed
文档 - http://developer.android.com/training/volley/index.html
答案 1 :(得分:0)
您必须将服务器放入网络中。之后,您可以使用计算机的IpAdress访问。 我从来没有用Wamp服务器做过这个。
How to enable local network users to access my WAMP sites?
要连接Android手机,您可以使用HttpUrlConnection:http://developer.android.com/reference/java/net/HttpURLConnection.html
如果要显示WebPage,可以使用WebView:http://developer.android.com/reference/android/webkit/WebView.html
这是我的类连接到服务器。 我在构造函数中放入了一个Listner。监听器是实现接口的类。有了它,你可以覆盖接口的方法,当asyn任务完成时(onPostExecute中的listner.onTaskCompleted),方法就是调用。
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());
}
}
}
答案 2 :(得分:0)
“localhost”地址始终只指向您呼叫它的设备。
示例:如果您从您的wamp计算机呼叫/导航到“localhost”,它将返回从您的计算机提供的内容。如果您在Android设备上执行相同操作,它将返回您从Android设备提供的内容。
据我所知,您的问题是您想从Android设备上的应用程序访问您的wamp服务器。 为此,您应该将您的Android应用程序的网络请求发送到运行wamp服务器的计算机的ip地址(而不是“localhost”)。 您可以通过在cmd(windows)中调用“ipconfig”或在终端(linux)中调用“ifconfig”来获取计算机的IP。
在你的应用程序中你应该使用Http(s)URLConnection,你需要在非UI线程中使用它,这样它就不会崩溃你的应用程序。你可以使用AsyncTask。
以下是此示例代码:
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();
}
}
有关HttpsURLConnection和AsyncTask的更多信息,请参阅以下页面: http://developer.android.com/reference/javax/net/ssl/HttpsURLConnection.html
http://developer.android.com/reference/android/os/AsyncTask.html