Basic authentication for accessing the rest apis assembly from android

I want to use apis build from android environment for my project. I am trying to do basic authentication as follows:

String authentication = "username:password"; String encoding = Base64.encodeToString(authentication.getBytes(), 0); URL url = new URL("https://www.assembla.com/"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Authorization", "Basic " + encoding); conn.setDoOutput(true); conn.connect(); System.out.println(conn.getResponseCode()); System.out.println(conn.getResponseMessage()); 

I get 400 and Bad Request in the output. Is something wrong with the URL I'm using, or is something else going wrong?

+6
source share
2 answers

It seems that this question has been answered here . You should use the Base64.NO_WRAP flag when encoding a pair of username and password:

 String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP); 

By default, Android Base64 util adds a newline to the end of the encoded string. This invalidates the HTTP headers and causes a Bad Request.

The Base64.NO_WRAP flag instructs the utility to create an encoded string without a newline, thereby preserving intact HTTP headers.

+6
source

REST API with HTTP authentication output: - I got the result

 String authentication = "username:password"; String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setRequestProperty ("Authorization", "Basic " + encoding); conn.connect(); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write( data ); wr.flush(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while((line = reader.readLine()) != null) { // Append server response in string sb.append(line + "\n"); } Content = sb.toString(); 
0
source

Source: https://habr.com/ru/post/895314/


All Articles