FileNotFoundException when using http: // user: [email protected]

0

I am trying to access a file that I have on a server, which is protected with .htpasswd . And when trying to access from my app in android I get the following exception:

  

java.io.FileNotFoundException:    link

The code I use is:

URL url = new URL(urlString);

// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str = in.readLine();
in.close();
    
asked by 20.06.2017 в 12:29
source

1 answer

1

That of adding the user and password in the url http://user:[email protected] is a slightly dirty shortcut that only some browsers implement (and it seems that less and less). It is not recommended. And it is logical that Java does not walk.

To connect with HTTP with authentication (Basic), there is several ways , but all resolve to code the string <usuario>:<clave> in Base64 and add it as property "Authorization" in the connection:

URL url = new URL(path);
String userPass = "username:password";
String basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT);
//o String basicAuth = "Basic " + new String(Base64.encode(userPass.getBytes(), Base64.No_WRAP));
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("Authorization", basicAuth);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
    
answered by 20.06.2017 / 15:12
source