2016-05-30 80 views
-1

我尝试设置HttpURLConnection。我使用Google documentation的语法。我想将字符串'phonenumber'和字符串'password'发送到Web服务器。这是我的java文件:尝试在android studio中设置HttpURLConnection时出现'未处理的异常'

public class Login extends AppCompatActivity { 

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

     EditText phonenumberText = (EditText)findViewById(R.id.phonenumberText); 
     EditText passwordText = (EditText)findViewById(R.id.passwordText); 
     String phonenumber = phonenumberText.getText().toString(); 
     String password = passwordText.getText().toString(); 
     String web = "webadress/login/tel=" + phonenumber + "&password =" + password; 

     URL url = new URL(web); 
     HttpURLConnection client = (HttpURLConnection) url.openConnection(); 

     try{ 
      InputStream in = new BufferedInputStream(client.getInputStream()); 
      readStream(in); 
      finally { 
       client.disconnect(); 
      }//finally 
     }//try 

    }//onCreate 
}//Login 

在AndroidManifest我包括

<uses-permission android:name="android.permission.INTERNET" /> 

,但我得到的方法url.openConnection()client.getInputStream()readStream(in)错误未处理的异常:java.io.IOException的。对于new URL(web),我得到错误未处理的异常:java.net.MalformedURLException。帮助将不胜感激。

+0

阅读此:https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html –

+0

您正在调用抛出检查异常的方法,因此您需要捕获它们。这就是它的工作原理。 – Mena

+0

我是一名初学者:捕捉方法的含义是什么? – Izotz

回答

0

您需要将全部语句包含在try/catch块中,而不仅仅是最后两个中的IoException。事情是这样的:

//your existing code.. 

HttpURLConnection client = null; 

try{ 
    URL url = new URL(web); 
    client = (HttpURLConnection) url.openConnection(); 

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

} catch (MalformedURLException e) { 
    //bad URL, tell the user 
} catch (IOException e) { 
    //network error/ tell the user 
} finally { 
    client.disconnect(); 
} 

具体而言:在catch块用于“捕获”了异常,例如。当出现网络错误或URL无效时,控制权将从您可以从的地方转移到catch区块。告诉用户有错误。

+0

谢谢,但它无法解决客户端。只在'client.disconnect()' – Izotz

+0

@Izotz,修正,抱歉。你需要把'HttpURLConnection客户端'放在catch块之外 – JonasCz

+0

finally语句中的变量'client'可能没有初始化' – Izotz

相关问题