java.net.MalformedURLException 在 android 中访问 asp.net Web API

java.net.MalformedURLException in android while accessing asp.net Web API

我看过这个 question,我的情况不是这样,因为我的 url、
中没有反斜杠 我有简单的 URL,比如 https://url.com/login

我的代码,

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class LoginActivity extends AppCompatActivity {

    URL url = new URL("https://url.net/login/");


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

        FloatingActionButton btn = (FloatingActionButton) findViewById(R.id.submitbtn);
        EditText edtxt = (EditText) findViewById(R.id.usernm);
        EditText edtxt2 = (EditText) findViewById(R.id.usrpwd);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(),HomeActivity.class);
                startActivity(i);
            }
        });

        HttpURLConnection urlConnection = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            readStream(in);
        } finally {
            urlConnection.disconnect();
        }
    }
}

屏幕截图:

当我将鼠标悬停在 new URL(); 上时,我得到 error 作为:

Unhandled Exception: java.net.MalformedURLException

这就是为什么我在行中收到另一个错误,

InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);

在堆栈跟踪中我得到 错误 作为,

Error:(48, 13) error: cannot find symbol method readStream(InputStream)

When I hover on new URL();, I get error as:

URL() 构造函数抛出 java.net.MalformedURLException。您需要将该构造函数调用包装在 try/catch 块中。

That's why I'm getting another error at line,

那是因为 getInputStream() 也会抛出已检查的异常。您需要将该代码包装在 try/catch 块中。

That's the line of error and I'm getting error as Error:(48, 13) error: cannot find symbol method readStream(InputStream)

那是因为你没有在这个class上实现一个名为readStream()的方法。

所有关于 Java 编程的好书或课程都涵盖了所有这些内容。

最终,一旦您克服了这些编译错误,您的代码将在运行时崩溃并显示 NetworkOnMainThreadException,因为您无法在主应用程序线程上执行网络 I/O。您需要将此 HTTP 代码移动到后台线程,您可以自己创建线程,也可以使用可以为您处理它的 HTTP 客户端 API(例如,OkHttp)。