2015-06-02 33 views
0
try{ 
    String a="http://10.0.2.2/test2.php"; 
    Log.d("URL",a); 
    url = new URL(a); 
    Log.d("URL23",a); 

    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); 
    Log.d("URL3",a); 

    try { 
     System.setProperty("http.keepAlive", "false"); 
     // just want to do an HTTP GET here 
     urlConnection.setRequestMethod("GET"); 

     urlConnection.setRequestProperty("Content-length", "0"); 
     urlConnection.setUseCaches(false); 
     urlConnection.setAllowUserInteraction(false); 
     // give it 15 seconds to respond 
     urlConnection.setReadTimeout(35 * 1000); 
     urlConnection.connect(); 

     int status = urlConnection.getResponseCode(); 

     switch (status) { 
      case 200:Log.d("CASE","@@@@@@@@@@@@@@@@  200"); 
      case 201: 
       BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 
       StringBuilder sb = new StringBuilder(); 
       String line; 
       while ((line = br.readLine()) != null) { 
        sb.append(line+"\n"); 
       } 
       br.close(); 
       Log.d("CASE 201 String",sb.toString()); 
     } 
    } 
} 

它是在getResponseCode抛出异常,并且还在urlConnection.getInputStream()(如果不使用开关的情况)。任何人都可以请告诉我为什么我无法建立连接使用HttpURLConnection和我的代码错误。HttpURLConnection类(未建立的连接)

+0

您是否在清单中指定了Internet权限? –

+0

是的,我已经使用模拟器或从设备添加权限 – user2796222

+0

,因为您正在访问本地url? –

回答

1

听起来像您的本地网站不能通过您的设备访问。 找到问题或让它在您的设备上运行,然后再次尝试它将工作的相同过程。 如果您使用本地网站与android编程本地网站必须可以通过用于测试的设备访问。因此,请在LAN网络上正确配置站点,并将您的设备连接到同一网络上。