基本auth服务器响应未经授权

时间:2016-12-19 06:00:21

标签: android

我是android的新手,我正在使用服务器调用登录Basic Auth,如果我在用户ID服务器响应中以超过45个字母登录为未授权,则一切正常。如果用户ID小于45个字母,则接受 我的服务器调用如下

HttpURLConnection conn=null;
URL url = new URL(url string);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setReadTimeout(60000); 
String basicAuth = "Basic " + new String(Base64.encode(Username+":"+Password));
conn.setRequestProperty ("Authorization", basicAuth);
conn.connect();

这里是conn.connect();本身抛出401:UnAuthorized

2 个答案:

答案 0 :(得分:0)

   HttpURLConnection conn=null;
   URL url = new URL(url string);
   conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("POST");
   conn.setDoOutput(true);
   conn.setDoInput(true);
   conn.setReadTimeout(60000); 
   String publicKey = "Username:Password";//getting your key
   String encodedString = Base64.encodeToString(publicKey.getBytes(), Base64.NO_WRAP);
   String basicAuth = "Basic "+ encodedString; //space after Basic is matter.
   //setting header for authentication purpose, should use authorization as keyword it you change this it won't work anymore
   conn.setRequestProperty("Authorization", basicAuth);
   conn.connect();

答案 1 :(得分:0)

代码如下:

String credentials = String.format("%s:%s", "username", "password");  
String basicAuth = "Basic "+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
HttpURLConnection conn=null;
URL url = new URL(url string);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setReadTimeout(60000); 
conn.setRequestProperty ("Authorization", basicAuth);
conn.connect();