PHPirate PHPirate - 1 year ago 127
Android Question

Android: not getting xml out of http get request with basic authentication

My goal is to get the xml from an API. The API uri I use, including parameters is I am given a username and password, for what I think probably is basic authorization.

I tried various things like something with an Authenticator, the format, but at the end of a lot of SO searching I ended up with something with a

with the basic authorization.

I put the code into an AsyncTask which seems to work correctly so I will just put the code from inside
in here.

As the java
I first got didn't give me much information, I found out how to use the
to find out more.

InputStream in;
int resCode;

try {
URL url = new URL("");

String userCredentials = "username:password";
String encoding = new String(android.util.Base64.encode(userCredentials.getBytes(), Base64.DEFAULT));

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + encoding);

try {
resCode = urlConnection.getResponseCode();
if (resCode == HttpURLConnection.HTTP_OK) {
in = urlConnection.getInputStream();
} else {
Log.i("rescode","not ok");
in = urlConnection.getErrorStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
return stringBuilder.toString();
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;

Then, in
I print the response, but the response I get is

<?xml version="1.0"?>
<soap:Envelope xmlns:soap="" soap:encodingStyle="">
<faultstring>006:No customer found for the specified username and password</faultstring></soap:Fault>

This is of course not right, it should give a full xml of in this case a train voyage recommendation.

I tested with my browsers, and also using a HTTP request tool called Postman which returned the correct xml so all the uri's, parameters, username and password are correct.

Answer Source

The encoding used is wrong. The base64 encoding used randomly returns whitespaces in the middle, adding encoding = encoding.replaceAll("\\s+",""); actually fixed it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download