java - Retrofit 无法连接到 hapi 服务器 localhost?

标签 java android retrofit2 hapi.js

我正在构建 android 应用程序,使用改造作为我的 httprequest 连接到我的 hapi 服务器。我的服务器运行良好,我已经在 postman 和我的 WebApps 上对其进行了测试。但是我的改造无法连接到它。下面是我的代码。为了便于阅读,我删除了不需要的行:

登录 Activity .java

package com.sianghee.reviu;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.ButterKnife;
import butterknife.BindView;
import butterknife.OnClick;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import com.sianghee.reviu.interfaces.APIService;
import com.sianghee.reviu.lib.Session;
import com.sianghee.reviu.models.UserLogin;
import static com.sianghee.reviu.lib.Helper.returnError;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class LoginActivity extends Activity {
    private static final String TAG = "LoginActivity";
    private static final int REQUEST_SIGNUP = 0;
    Session session;
    public static final String BASE_URL = "localhost:3000";

    private EditText emailText;
    private EditText passwordText;

     @BindView(R.id.btn_login) Button _loginButton;
    @BindView(R.id.link_signup) TextView _signupLink;

    // TODO: Init sewaktu pertama kali form diload
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        emailText = (EditText)findViewById(R.id.input_email);
        passwordText = (EditText)findViewById(R.id.input_password);

    }

    // TODO: bind login and do login
    @OnClick(R.id.btn_login)
    public void submitLogin() {
        login();
    }

    // TODO: bind signup and do register
    ....

    public void login() {
        Log.d(TAG, "Login");

        if (!validate()) {
            onLoginFailed();
            return;
        }

        _loginButton.setEnabled(false);

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("Authenticating...");
        progressDialog.show();

        String email = emailText.getText().toString();
        String password = passwordText.getText().toString();

        // TODO: Implement your own authentication logic here.
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        APIService api = retrofit.create(APIService.class);
        UserLogin userLogin = new UserLogin(email, password);

        Call<UserLogin> call = api.login(userLogin);
        call.enqueue(new Callback<UserLogin>() {
            @Override
            public void onResponse(Call<UserLogin> call, Response<UserLogin> response) {
                String result;
                progressDialog.dismiss();
                try {
                    result = response.body().toString();

                    if (returnError(result).isEmpty()) {

                        JSONObject obj;
                        obj = new JSONObject(result);
                        session.setLoginSession(obj.getString("scope"), obj.getString("token"));

                        Intent i = new Intent(LoginActivity.this, MainActivity.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(i);
                        finish();

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            .......
}

APIService.java

package com.sianghee.reviu.interfaces;

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;

import com.sianghee.reviu.models.UserLogin;

/**
 * Created by andy on 11/26/17.
 */

public interface APIService {
    @POST("auth")
    Call<UserLogin> login(@Body UserLogin auth);
}

用户登录.java

package com.sianghee.reviu.models;

public class UserLogin {
    String email;
    String password;

    public UserLogin(String email, String password) {
        this.email = email;
        this.password = password;
    }
}

每当我点击登录按钮时,都无法连接到服务器。下面是 logcat:

12-02 23:24:42.771 3660-3660/com.sianghee.reviu I/InstantRun: starting instant run server: is main process
12-02 23:24:43.116 3660-3690/com.sianghee.reviu D/OpenGLRenderer: HWUI GL Pipeline
12-02 23:24:43.213 3660-3660/com.sianghee.reviu I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
12-02 23:24:43.219 3660-3660/com.sianghee.reviu I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.

                                                                   [ 12-02 23:24:43.283  3660: 3690 D/         ]
                                                                   HostConnection::get() New Host Connection established 0x896438c0, tid 3690
12-02 23:24:43.471 3660-3690/com.sianghee.reviu I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
12-02 23:24:43.471 3660-3690/com.sianghee.reviu I/OpenGLRenderer: Initialized EGL, version 1.4
12-02 23:24:43.471 3660-3690/com.sianghee.reviu D/OpenGLRenderer: Swap behavior 1
12-02 23:24:43.471 3660-3690/com.sianghee.reviu W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
12-02 23:24:43.471 3660-3690/com.sianghee.reviu D/OpenGLRenderer: Swap behavior 0
12-02 23:24:43.473 3660-3690/com.sianghee.reviu D/EGL_emulation: eglCreateContext: 0x9b543860: maj 2 min 0 rcv 2
12-02 23:24:43.475 3660-3690/com.sianghee.reviu D/EGL_emulation: eglMakeCurrent: 0x9b543860: ver 2 0 (tinfo 0xa4a8f700)
12-02 23:24:43.527 3660-3690/com.sianghee.reviu D/EGL_emulation: eglMakeCurrent: 0x9b543860: ver 2 0 (tinfo 0xa4a8f700)
12-02 23:24:43.856 3660-3660/com.sianghee.reviu I/AssistStructure: Flattened final assist data: 1684 bytes, containing 1 windows, 5 views
12-02 23:24:49.113 3660-3673/com.sianghee.reviu I/zygote: Do partial code cache collection, code=30KB, data=26KB
12-02 23:24:49.113 3660-3673/com.sianghee.reviu I/zygote: After code cache collection, code=30KB, data=26KB
12-02 23:24:49.113 3660-3673/com.sianghee.reviu I/zygote: Increasing code cache capacity to 128KB
12-02 23:24:51.355 3660-3673/com.sianghee.reviu I/zygote: Do partial code cache collection, code=61KB, data=59KB
12-02 23:24:51.356 3660-3673/com.sianghee.reviu I/zygote: After code cache collection, code=61KB, data=59KB
12-02 23:24:51.356 3660-3673/com.sianghee.reviu I/zygote: Increasing code cache capacity to 256KB
12-02 23:24:54.016 3660-3673/com.sianghee.reviu I/zygote: Do full code cache collection, code=123KB, data=99KB
12-02 23:24:54.016 3660-3673/com.sianghee.reviu I/zygote: After code cache collection, code=107KB, data=66KB
12-02 23:24:56.503 3660-3660/com.sianghee.reviu D/LoginActivity: Login
12-02 23:24:56.573 3660-3673/com.sianghee.reviu I/zygote: Do partial code cache collection, code=114KB, data=93KB
12-02 23:24:56.573 3660-3673/com.sianghee.reviu I/zygote: After code cache collection, code=114KB, data=93KB
12-02 23:24:56.573 3660-3673/com.sianghee.reviu I/zygote: Increasing code cache capacity to 512KB
12-02 23:24:56.574 3660-3673/com.sianghee.reviu I/zygote: JIT allocated 56KB for compiled code of void android.view.View.<init>(android.content.Context, android.util.AttributeSet, int, int)
12-02 23:24:56.603 3660-3660/com.sianghee.reviu D/NetworkSecurityConfig: No Network Security Config specified, using platform default
12-02 23:24:56.803 3660-3660/com.sianghee.reviu W/error: java.net.ConnectException: Failed to connect to /127.0.0.1:3000
12-02 23:24:57.094 3660-3690/com.sianghee.reviu D/EGL_emulation: eglMakeCurrent: 0x9b543860: ver 2 0 (tinfo 0xa4a8f700)
12-02 23:24:57.126 3660-3690/com.sianghee.reviu D/EGL_emulation: eglMakeCurrent: 0x9b543860: ver 2 0 (tinfo 0xa4a8f700)

我用于登录的服务器 API Url 是: http://127.0.0.1:3000/auth

请注意我的 Log.w() 方法中的错误:

java.net.ConnectException: Failed to connect to /127.0.0.1:3000

也许这只是我的常见错误,请帮助。

最佳答案

127.0.0.1 是您机器的本地主机/环回地址(托管服务器)。 127.0.0.1 映射到机器的 IP 地址,因此 http://127.0.0.1:3000/auth 只能从您的机器访问。

现在,为了从任何其他机器(即您的手机)访问 http://127.0.0.1:3000/auth,您的机器(服务器)和设备(手机)应该在同一个网络上(例如同一个 Wi-Fi) 您需要通过 http://IPAddressOfYourMachine:3000/auth 访问它。

在 MacOs/Linux 上,您可以在终端上使用 ifconfig 命令找出 IP 地址。在 Windows 机器上,命令是 ipconfig。 IP 地址应为 192.168.x.y 的形式。

所以最终的 BASE_URL 应该类似于 http://192.168.x.y:3000

关于java - Retrofit 无法连接到 hapi 服务器 localhost?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47609995/

相关文章:

java - 强制 Hibernate 插入而不使用 Select 语句

Java简单服务器客户端

java - 使用QuickBooks Web Connector的身份验证问题:对象引用未设置为对象的实例

java - 改造自定义超时不起作用

java - 格式化输入字符串数组

java - 将 JAR 文件添加到测试类路径 :

android - 如何删除 fragment onFling手势Android

android - 获取 Android 数据使用历史的最详细信息

android - JSON 数据解析 - 如何?

java - toArray 与预先调整大小的数组