2016-01-18 55 views
0

我是这个网站的新手,所以如果我做错了,请告诉我。Android中的http请求问题

我想建立我的node.js服务器和我的android应用程序之间的连接。例如,我试图连接一个名为showWithAuth的页面,我需要使用摘要stategy进行身份验证。

为此我使用验证器:

Authenticator.setDefault(new Authenticator() 
      { 
       @Override 
       protected PasswordAuthentication getPasswordAuthentication() 
       { 
        return new PasswordAuthentication (username, password.toCharArray()); 
        // System.out.println(pa.getUserName() + ":" + new String(pa.getPassword())); 
       } 
      }); 

我真正的问题是,当我尝试建立连接:

try { 
       URL url = new URL(strURL); 
       HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
       in = new BufferedReader(new InputStreamReader(connection 
         .getInputStream())); 

       String line; 

       while ((line = in.readLine()) != null) { 
        sb.append(line); 
       } 
       System.out.println(sb); 
       /*connection.setInstanceFollowRedirects(false); 
       int status = connection.getResponseCode(); 
       InputStream is; 

       if (status >= 400 && status <= 499) { 
        throw new Exception("Bad authentication status: " + status); //provide a more meaningful exception message 
       } 
       else 
       {*/ 
        //connection.setRequestProperty("User-Agent","Mozilla/5.0 (compatible) "); 
        //connection.setRequestProperty("Accept", "*/*"); 

        /*is = connection.getInputStream(); 
       } 

       byte[] buffer = new byte[8196]; 
       int readCount; 
       final StringBuilder builder = new StringBuilder(); 
       while ((readCount = is.read(buffer)) > -1) { 
        builder.append(new String(buffer, 0, readCount)); 
       } 
       String response = builder.toString(); 
       System.out.println(response);*/ 

      } catch (java.net.ProtocolException e) { 
       sb.append("User Or Password is wrong!"); 
       e.printStackTrace(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

的问题我已经是一个FileNotFoundException异常,在这一行:.getInputStream()));

服务器的响应是401:坏认证状态

我看到一些人遇到了同样的问题,但我尝试了每一个解决方案,但没有得到更好的结果。

如果你能帮我弄明白我做错了什么!谢谢 !

PS:评论的代码也尝试过。

PS2:抱歉这么久。

编辑:刚才也说,这个代码正在使用Java Netbeans的唯一,但不是在Android Studio中

回答

0

请通过添加

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

AndroidManifest.xml档案尝试,这可能会解决你的问题。

+0

我已经这样做了。顺便说一下,我已经做了另一个应用程序,可以连接我通过http发布网站,所以网站不是问题,我的互联网连接 –