2017-06-14 86 views
0

我已经看到了这个question,这不是我的情况,因为我没有反斜杠在我的网址,
我有简单的URL一样,https://url.com/loginjava.net.MalformedURLException android的asp.net的Web API

代码

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();,我得到错误为:

Unhandled Exception: java.net.MalformedURLException

这就是为什么我得到的线另一个错误,

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

在堆栈跟踪我得到错误如,

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

请将源代码作为文本发布,而不是图片。 – CommonsWare

+0

图像是错误的,这是错误的行,我得到错误为'错误:(48,13)错误:找不到符号方法readStream(InputStream)' –

回答

2

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)

这是因为您没有在此类上实施名为readStream()的方法。

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

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