Failed to connect to /192.168.43.23 (port 8000) from /192.168.43.1 (port 47726) after 10000ms

huangapple go评论91阅读模式
英文:

Failed to connect to /192.168.43.23 (port 8000) from /192.168.43.1 (port 47726) after 10000ms

问题

我正在使用Laravel REST APIAndroid Studio中创建一个登录活动。我在一个真实设备(Android版本9)上运行该应用程序。该API在Postman中运行正常,但在应用中却不行。我的计算机IP地址是192.168.43.23。当我尝试登录时,出现以下错误:Failed to connect to /192.168.43.23 (port 8000) from /192.168.43.1 (port 47726) after 10000ms。你有任何解决办法吗?谢谢。以下是我在LoginActivity.java中的代码:

private void login(String email, String password) {
    apiInterface = ApiClient.getClient().create(ApiInterface.class);
    Call<Login> loginCall = apiInterface.loginResponse(email, password);
    loginCall.enqueue(new Callback<Login>() {
        @Override
        public void onResponse(Call<Login> call, Response<Login> response) {
            if(response.body() != null && response.isSuccessful() && response.body().isStatus()){

                sessionManager = new SessionManager(LoginActivity.this);
                LoginData loginData = response.body().getLoginData();
                sessionManager.createLoginSession(loginData);

                Toast.makeText(LoginActivity.this, response.body().getLoginData().getEmail(), Toast.LENGTH_SHORT).show();
                Intent intentLogin = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intentLogin);
                finish();

            }else{
                Toast.makeText(LoginActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<Login> call, Throwable t) {
            Toast.makeText(LoginActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sessionManager = new SessionManager(MainActivity.this);
    if(!sessionManager.isLoggedIn()){
        moveToLogin();
    }
}

private void moveToLogin() {
    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
    startActivity(intent);
    finish();
}

ApiClient.Java:

public class ApiClient {
    private static final String BASE_URL = "http://192.168.43.23:8000/api/";

    private static Retrofit retrofit;

    public static Retrofit getClient() {
        if (retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

ApiInterface.java:

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface ApiInterface {
    @FormUrlEncoded
    @POST("loginPassenger")
    Call<Login> loginResponse(
            @Field("email") String email,
            @Field("password") String password
    );
}

Login.java:

import com.google.gson.annotations.SerializedName;

public class Login{
    @SerializedName("data")
    private LoginData loginData;

    @SerializedName("message")
    private String message;

    @SerializedName("status")
    private boolean status;

    // ... Getters and setters ...
}

LoginData.java:

import com.google.gson.annotations.SerializedName;

public class LoginData {
    // ... Fields ...

    // ... Getters and setters ...
}

AndroidManifest.xml:

<!-- AndroidManifest.xml 部分略 -->

build.gradle:

// build.gradle 部分略

network_security_config.xml:

<!-- network_security_config.xml 部分略 -->
英文:

I am creating a Login Activity in Android Studio using Laravel REST API. I run the application on a real device (Android version 9). The API worked in Postman but not in the app. My computer's IP address is 192.168.43.23. When I try to login, here's the error Failed to connect to /192.168.43.23 (port 8000) from /192.168.43.1 (port 47726) after 10000ms. Do you have any idea how to solve it? Thank you. Here's my code in LoginActivity.java:

private void login(String email, String password) {
    apiInterface = ApiClient.getClient().create(ApiInterface.class);
    Call&lt;Login&gt; loginCall = apiInterface.loginResponse(email, password);
    loginCall.enqueue(new Callback&lt;Login&gt;() {
        @Override
        public void onResponse(Call&lt;Login&gt; call, Response&lt;Login&gt; response) {
            if(response.body() != null &amp;&amp; response.isSuccessful() &amp;&amp; response.body().isStatus()){

                sessionManager = new SessionManager(LoginActivity.this);
                LoginData loginData = response.body().getLoginData();
                sessionManager.createLoginSession(loginData);

                Toast.makeText(LoginActivity.this, response.body().getLoginData().getEmail(), Toast.LENGTH_SHORT).show();
                Intent intentLogin = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intentLogin);
                finish();

            }else{
                Toast.makeText(LoginActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call&lt;Login&gt; call, Throwable t) {
            Toast.makeText(LoginActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();

        }
    });

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sessionManager = new SessionManager(MainActivity.this);
    if(!sessionManager.isLoggedIn()){
        moveToLogin();
    }
}

private void moveToLogin() {
    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
    startActivity(intent);
    finish();
}

ApiClient.Java

public class ApiClient {
private static final String BASE_URL = &quot;http://192.168.43.23:8000/api/&quot;;

private static Retrofit retrofit;

public static Retrofit getClient() {
    if (retrofit == null){
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

ApiInterface.java

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface ApiInterface {

   @FormUrlEncoded
   @POST(&quot;loginPassenger&quot;)
   Call&lt;Login&gt; loginResponse(
        @Field(&quot;email&quot;) String email,
        @Field(&quot;password&quot;) String password
   );
 }

Login.java

import com.google.gson.annotations.SerializedName;

public class Login{

   @SerializedName(&quot;data&quot;)
   private LoginData loginData;

   @SerializedName(&quot;message&quot;)
   private String message;

   @SerializedName(&quot;status&quot;)
   private boolean status;

   public void setLoginData(LoginData loginData){
	   this.loginData = loginData;
   }

   public LoginData getLoginData(){
	   return loginData;
   }

   public void setMessage(String message){

	   this.message = message;
   }

   public String getMessage(){
	   return message;
   }

   public void setStatus(boolean status){
	   this.status = status;
   }

   public boolean isStatus(){
	   return status;
   }
   }

LoginData.java

import com.google.gson.annotations.SerializedName;

public class LoginData {

   @SerializedName(&quot;password&quot;)
   private String password;

   @SerializedName(&quot;contact&quot;)
   private String contact;

   @SerializedName(&quot;name&quot;)
   private String name;

   @SerializedName(&quot;updated_at&quot;)
   private Object updatedAt;

   @SerializedName(&quot;id_users&quot;)
   private String idUsers;

   @SerializedName(&quot;created_at&quot;)
   private Object createdAt;

   @SerializedName(&quot;gender&quot;)
   private int gender;

   @SerializedName(&quot;email&quot;)
   private String email;

   @SerializedName(&quot;username&quot;)
   private String username;

   @SerializedName(&quot;address&quot;)
   private String address;

   public void setPassword(String password){
	   this.password = password;
   }

   public String getPassword(){
	   return password;
   }

   public void setContact(String contact){
	   this.contact = contact;
   }

   public String getContact(){
	   return contact;
   }

   public void setName(String name){
	   this.name = name;
   }

   public String getName(){
	   return name;
   }

   public void setUpdatedAt(Object updatedAt){
	   this.updatedAt = updatedAt;
   }

   public Object getUpdatedAt(){
	   return updatedAt;
   }

   public void setIdUsers(String idUsers){
	   this.idUsers = idUsers;
   }

   public String getIdUsers(){
	   return idUsers;
   }

   public void setCreatedAt(Object createdAt){
	   this.createdAt = createdAt;
   }

   public Object getCreatedAt(){
	   return createdAt;
   }

   public void setGender(int gender){
	   this.gender = gender;
   }

   public int getGender(){
	   return gender;
   }

   public void setEmail(String email){
	   this.email = email;
   }

   public String getEmail(){
	   return email;
   }

   public void setUsername(String username){
	   this.username = username;
   }

   public String getUsername(){
	   return username;
   }

   public void setAddress(String address){
	   this.address = address;
   }

   public String getAddress(){
	   return address;
   } 
   }

AndroidManifest.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
   package=&quot;com.example.passengerApp&quot;&gt;

   &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;
   &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;

   &lt;application
       android:icon=&quot;@mipmap/ic_launcher&quot;
       android:label=&quot;@string/app_name&quot;
       android:networkSecurityConfig=&quot;@xml/network_security_config&quot;
       android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
       android:supportsRtl=&quot;true&quot;
       android:theme=&quot;@style/AppTheme&quot;
       android:usesCleartextTraffic=&quot;true&quot;&gt;
       &lt;activity android:name=&quot;.AccountActivity&quot;/&gt;
       &lt;activity android:name=&quot;.MyOrderActivity&quot; /&gt;
       &lt;activity android:name=&quot;.RegisterActivity&quot; /&gt;
       &lt;activity android:name=&quot;.LoginActivity&quot; /&gt;
       &lt;activity android:name=&quot;.MainActivity&quot;&gt;
           &lt;intent-filter&gt;
               &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;

               &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
           &lt;/intent-filter&gt;
       &lt;/activity&gt;
   &lt;/application&gt;

</manifest>

build.gradle

apply plugin: &#39;com.android.application&#39;

android {
    compileSdkVersion 30
    buildToolsVersion &quot;30.0.1&quot;

    defaultConfig {
        applicationId &quot;com.example.passengerApp&quot;
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName &quot;1.0&quot;

        testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard- rules.pro&#39;
        }
    }
}

dependencies {
    implementation fileTree(dir: &quot;libs&quot;, include: [&quot;*.jar&quot;])
    implementation &#39;androidx.appcompat:appcompat:1.2.0&#39;
    implementation &#39;androidx.constraintlayout:constraintlayout:2.0.2&#39;
    implementation &#39;com.google.android.material:material:1.2.1&#39;
    implementation &#39;androidx.annotation:annotation:1.1.0&#39;
    implementation &#39;androidx.lifecycle:lifecycle-extensions:2.2.0&#39;
    implementation &#39;com.android.support:design:30&#39;
    testImplementation &#39;junit:junit:4.12&#39;
    androidTestImplementation &#39;androidx.test.ext:junit:1.1.2&#39;
    androidTestImplementation &#39;androidx.test.espresso:espresso-core:3.3.0&#39;

    implementation &#39;com.squareup.retrofit2:retrofit:2.6.1&#39;
    implementation &#39;com.squareup.retrofit2:converter-gson:2.6.1&#39;
    implementation &#39;org.glassfish:javax.annotation:10.0-b28&#39;

    implementation &#39;com.google.code.gson:gson:2.8.5&#39;
}

network_security_config.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;network-security-config&gt;
&lt;base-config cleartextTrafficPermitted=&quot;true&quot; /&gt;
    &lt;domain-config cleartextTrafficPermitted=&quot;true&quot;&gt;
        &lt;domain includeSubdomains=&quot;true&quot;&gt;192.168.43.23:8000&lt;/domain&gt;
    &lt;/domain-config&gt;
&lt;/network-security-config&gt;

答案1

得分: -1

你的 API 是否能够在手机浏览器上正常工作?
检查一下你的 API 是否能够从 Chrome 或任何智能手机浏览器发送正确的响应。

英文:

is your api working from the browser of your phone?
check to see if your api sends the right response from chrome or any browser from your smartphone.

huangapple
  • 本文由 发表于 2020年10月18日 21:38:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64413993.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定