Android studio-本地主机连接文件未找到?

时间:2018-12-28 07:01:11

标签: java android django apache xampp

因此,我一直在尝试在我的应用程序上创建身份验证功能,以便用户可以登录。我正在尝试将JSON对象发送到我的Django REST API,以便我的用户可以获取令牌。

但是,每当我使用有效的用户凭据(me)按下登录后,即使我可以在浏览器中访问它,我的logcat也会向http://192.168.0.18:8000/token-auth/抛出未找到的文件异常。

我正在通过Macbook Pro中的XAMPP运行Django REST API。我的Android模拟器正在桌面上运行。借助Macbook Pro中的ReactJS应用程序,我能够执行类似的操作,在那里我可以从Django REST API中检索数据。

我已经将<uses-permission android:name="android.permission.INTERNET" />放在了manifest.xml中,它解决了我的权限问题。

下面是我的代码:

login.java

public class Login extends AppCompatActivity {

    Button LoginButton;
    EditText uUserName, uPassWord;
    WSAdapter.SendAPIRequests AuthHelper;

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

        //SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);

        LoginButton = (Button) findViewById(R.id.LoginButton);

        uUserName = (EditText) findViewById(R.id.LoginUserBox);
        uPassWord = (EditText) findViewById(R.id.LoginPassBox);

        //AuthHelper = new WSAdapter().new SendDeviceDetails();

        // Moves user to the main page after validation
        LoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // gets the username and password from the EditText
                String strUserName = uUserName.getText().toString();
                String strPassWord = uPassWord.getText().toString();

                // API url duh
                String APIUrl = "http://192.168.0.18:8000/token-auth/";

                // If the user is authenticated, then transfer to the MainActivity page
                if (APIAuthentication(strUserName, strPassWord, APIUrl)){
                    startActivity(new Intent(Login.this, MainActivity.class));
                }
            }
        });

    }

    private boolean APIAuthentication(String un, String pw, String url){
        // when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
        AuthHelper = new WSAdapter.SendAPIRequests();

        JSONObject postData = new JSONObject();
        try {
            // Attempt to input info to the Django API
            postData.put("username", un);
            postData.put("password", pw);

            // Putting the data to be posted in the Django API
            AuthHelper.execute(url, postData.toString());

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

        return false;
    }
}

WSAdapter.java

// I forgot what WS stands for, but this class serves as an adapter for JSON and Online stuff
// I think it stands for With-Server Adapter
public class WSAdapter extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    static public class SendAPIRequests extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

            Log.e("TAG", params[0]);
            Log.e("TAG", params[1]);
            String data = "";

            HttpURLConnection httpURLConnection = null;
            try {

                // Sets up connection to the URL (params[0] from .execute in "login")
                httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();

                // Sets the request method for the URL
                httpURLConnection.setRequestMethod("POST");

                // Tells the URL that I am sending a POST request body
                httpURLConnection.setDoOutput(true);

                // To write primitive Java data types to an output stream in a portable way
                DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
                // Writes out a byte to the underlying output stream of the data posted from .execute function
                wr.writeBytes("postData=" + params[1]);
                // Flushes the postData to the output stream
                wr.flush();
                wr.close();

                // Representing the input stream
                InputStream in = httpURLConnection.getInputStream();

                // Preparing input stream bytes to be decoded to charset
                InputStreamReader inputStreamReader = new InputStreamReader(in);
                StringBuilder dataBuffer = new StringBuilder();

                // Translates input stream bytes to charset
                int inputStreamData = inputStreamReader.read();
                while (inputStreamData != -1) {
                    char current = (char) inputStreamData;
                    inputStreamData = inputStreamReader.read();
                    // concatenates data characters from input stream
                    dataBuffer.append(current);
                }
                data = dataBuffer.toString();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // Disconnects socket after using
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }

            Log.e("TAG", data);
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // expecting a response code fro my server upon receiving the POST data
            Log.e("TAG", result);
        }
    }


}

以下是关于该问题的日志:

12-28 00:57:13.659 9025-9057/com.example.android.androidcraftsappprototype E/TAG: http://192.168.0.18:8000/token-auth/
    {"username":"erichardson","password":"ellyrichardson"}
12-28 00:57:13.743 9025-9057/com.example.android.androidcraftsappprototype D/NetworkSecurityConfig: No Network Security Config specified, using platform default
12-28 00:57:13.990 9025-9051/com.example.android.androidcraftsappprototype D/EGL_emulation: eglMakeCurrent: 0xa0f86f00: ver 2 0 (tinfo 0xa8d9b540)
12-28 00:57:14.038 9025-9051/com.example.android.androidcraftsappprototype D/EGL_emulation: eglMakeCurrent: 0xa0f86f00: ver 2 0 (tinfo 0xa8d9b540)
12-28 00:57:14.039 9025-9057/com.example.android.androidcraftsappprototype W/System.err: java.io.FileNotFoundException: http://192.168.0.18:8000/token-auth/
12-28 00:57:14.040 9025-9057/com.example.android.androidcraftsappprototype W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:251)
        at com.example.android.androidcraftsappprototype.WSAdapter$SendAPIRequests.doInBackground(WSAdapter.java:56)
        at com.example.android.androidcraftsappprototype.WSAdapter$SendAPIRequests.doInBackground(WSAdapter.java:26)
        at android.os.AsyncTask$2.call(AsyncTask.java:333)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)
12-28 00:57:14.118 9025-9051/com.example.android.androidcraftsappprototype D/EGL_emulation: eglMakeCurrent: 0xa0f86f00: ver 2 0 (tinfo 0xa8d9b540)
12-28 00:57:14.176 9025-9051/com.example.android.androidcraftsappprototype D/EGL_emulation: eglMakeCurrent: 0xa0f86f00: ver 2 0 (tinfo 0xa8d9b540)
12-28 00:57:14.198 9025-9051/com.example.android.androidcraftsappprototype D/EGL_emulation: eglMakeCurrent: 0xa0f86f00: ver 2 0 (tinfo 0xa8d9b540)
12-28 00:57:14.209 9025-9051/com.example.android.androidcraftsappprototype D/OpenGLRenderer: endAllActiveAnimators on 0x8f1e9d00 (RippleDrawable) with handle 0x8eb4b900
12-28 00:57:14.217 9025-9051/com.example.android.androidcraftsappprototype D/EGL_emulation: eglMakeCurrent: 0xa0f86f00: ver 2 0 (tinfo 0xa8d9b540)

我期望它能够连接,但是由于某种原因它无法连接,我也不知道为什么。

下面是我的Django REST令牌认证API的代码。这很简单,因为我只将API身份验证网址放入了urls.py

urls.py

from django.contrib import admin
from django.urls import path, include
from rest_framework_jwt.views import obtain_jwt_token

urlpatterns = [
    path('api/', include('projects.urls')),
    path('admin/', admin.site.urls),
    path('token-auth/', obtain_jwt_token),
]

0 个答案:

没有答案