我尝试使用AsyncTask类使用android studio连接到我的本地主机xampp。这是AsyncTask,但是它给出了错误提示Failed to connect
to /10.0.2.2:800
我尝试了我的真实IP地址cmd-> ipconfig IPV4和其他一些技巧,但是 他们没有成功
belwow是我的应用程序结构
使用类的AsyncTask
package app.buil.land.food.doymaj.doymaj;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by ProgrammingKnowledge on 1/5/2016.
*/
public class backGroundActivities extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
backGroundActivities (Context ctx) {
context = ctx;
}
@Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://10.0.2.2:800/login.php";
if(type.equals("login")) {
try {
String phone_number = params[1];
// String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("phone_number","UTF-8")+"="+URLEncoder.encode(phone_number,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
Log.e("Line_from_php_server",result);
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
@Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
这是我的MainActivity
package app.buil.land.food.doymaj.doymaj;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText phone_Number;
EditText user_Name;
EditText pass_Word;
Button singButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// singButton = (Button)findViewById(R.id.sing_id);
// singButton.setOnClickListener(kyListener);
phone_Number =(EditText)findViewById(R.id.mobile_id);
user_Name =(EditText)findViewById(R.id.name_id);
pass_Word =(EditText)findViewById(R.id.p_id);
}
// Push_Identity db = new Push_Identity(this,"CustomerDatabas.db",null,1);
public boolean validate(EditText[] fields){
for(int i = 0; i < fields.length; i++){
EditText currentField = fields[i];
if(currentField.getText().toString().length() <= 0){
switch (i){
case 0:
Toast.makeText(getApplicationContext(),"شماره تلفن وارد نشده ",Toast.LENGTH_LONG).show() ;
break;
case 1:
Toast.makeText(getApplicationContext(),"نام کاربری وارد نشده ",Toast.LENGTH_LONG).show() ;
break;
case 2:
Toast.makeText(getApplicationContext(),"رمز وارد نشده ",Toast.LENGTH_LONG).show() ;
break;
}
return false;
}
}
return true;
}
//private View.OnClickListener kyListener = new View.OnClickListener() {
public void send_number(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
boolean fieldsOK = validate(new EditText[] { phone_Number, user_Name, pass_Word });
if (fieldsOK ==true){
String Phon = phone_Number.getText().toString();
Toast.makeText(getApplicationContext(),Phon,Toast.LENGTH_LONG);
// the Tooast dose not display anything
// it seems that the EditText is empty buy i enter the value in
// in it.
String type ="login";
backGroundActivities back = new backGroundActivities(this);
back.execute(type,Phon);
//
}
}
// };
}
XML
<EditText
android:id="@+id/mobile_id"
android:layout_width="match_parent"
android:layout_height="43dp"
android:background="@drawable/customized_edtitext"
android:drawablePadding="15dp"
android:paddingRight="10dp"
android:paddingLeft="15dp"
android:drawableRight="@drawable/ic_smartphone"
android:elevation="2dp"
android:textStyle="bold"
android:hint="@string/register_phone_commnet"
android:fontFamily="@font/iransansmedium"
android:textSize="12sp"
/>
<EditText
android:id="@+id/name_id"
android:layout_width="match_parent"
android:layout_height="43dp"
android:layout_below="@id/mobile_id"
android:background="@drawable/customized_edtitext1"
android:drawablePadding="15dp"
android:paddingRight="10dp"
android:paddingLeft="15dp"
android:drawableRight="@mipmap/ic_user"
android:elevation="2dp"
android:textStyle="bold"
android:hint="@string/register_user_commnet"
android:fontFamily="@font/iransansmedium"
android:textSize="12dp" />
<EditText
android:id="@+id/p_id"
android:layout_width="match_parent"
android:layout_height="43dp"
android:layout_below="@+id/name_id"
android:background="@drawable/customized_edtitext2"
android:drawablePadding="15dp"
android:paddingRight="10dp"
android:paddingLeft="15dp"
android:drawableRight="@mipmap/ic_unlocked"
android:elevation="2dp"
android:textStyle="bold"
android:hint="@string/register_pass_commnet"
android:fontFamily="@font/iransansmedium"
android:textSize="12sp"
android:paddingEnd="10dp" />
这是我的php页面的网址 enter image description here
还有更多信息:我已经安装了Genymotion,还安装了bluestack和VirtaulBox。他们对港口感到困惑吗?我的意思是这些软件可能导致Apache xampp端口及其端口冲突吗?
答案 0 :(得分:1)
我的Xampp正在使用端口: 80 ,如下图所示。因此,在IP地址下方写为OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
};
OkHttpClient client = httpClient.build();
Request request = new Request.Builder()
.url("URL")
.addHeader("Header", "123")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Log.d("OKHTTP3", e.getMessage());
// You get this failure
runOnUiThread(() -> {
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
final String _body = response.body().string();
Log.d("OKHTTP3", _body);
runOnUiThread(() -> {
});
} catch (InterruptedIOException e) {
runOnUiThread(() -> {
// Or this exception depending when timeout is reached
});
}
}
});
对我有用。
答案 1 :(得分:0)
如果您具有wifi,并且计算机和真实设备(移动设备)已连接到同一wifi,则可以使用NGROK软件工具在真实设备中运行和调试您的应用。
运行ngrok.exe并输入 ngrok http 80 ,它将为您提供一个如下图所示的地址。
只需在您使用IP地址的应用中使用该网址即可。 最好使用。
答案 2 :(得分:0)
此答案假定浏览器屏幕截图显示页面成功加载。我相信错误页面会更灰一些。
可能有一个防火墙问题。由于您使用的是非标准端口,因此XAMPP所安装的防火墙例外可能无法解决。
转到Windows防火墙高级设置->入站规则。现在,添加一条允许TCP端口800上的流量的规则。请确保取消选中公共配置文件,这样,如果您使用的是公共wifi,则没有人可以连接到该应用程序。
如果您的PHP应用程序可访问,请使用智能手机的浏览器进行检查。