0

我见过这个问题,这不是我的情况,因为我的网址中没有反斜杠,
所以我有简单的网址,例如,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();,出现以下错误

未处理的异常:java.net.MalformedURLException

这就是为什么我在网上遇到另一个错误,

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

在堆栈跟踪中我收到错误

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

1 回答 1

2

当我将鼠标悬停在 new URL(); 上时,出现以下错误:

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

这就是为什么我在网上遇到另一个错误,

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

这是错误行,我收到错误为 Error:(48, 13) error: cannot find symbol method readStream(InputStream)

那是因为您没有实现readStream()在此类上命名的方法。

所有这些都包含在任何关于 Java 编程的好书或课程中。

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

于 2017-06-14T14:34:47.663 回答