I want to download the content of html and json files from a webserver with http authentication on android.
On the browsers I always used http://username:passwort@example.com/path/to/something, which worked fine. But in Java on Android it doesn't work (it worked fine before adding HTTP Authoriziation). I can show a html file in the webview using this. But how to download the content? I always get FileNotFoundException
.
Code to download html file:
String url = "http://username:passwort@example.com/path/to/something";
//or: "http://example.com/path/to/something"
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
//error is thrown by the following line
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null)
{
stringBuilder.append(inputLine + "\n");
}
return stringBuilder.toString();
Another way I tried to download the json File:
URL url = new URL(urlstring);
String encoding = Base64.encode("username:password".getBytes(), Base64.DEFAULT).toString();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + encoding);
//error is thrown in the following line
is = (InputStream) connection.getInputStream();
or using DefaultHttpClient instead of HttpURLConnection
URL url = new URL(urlstring);
String encoding = Base64.encode("username:password".getBytes(), Base64.DEFAULT).toString();
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlstring);
httpPost.setHeader("Authorization", "Basic " + encoding);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
in the end I want to read the content:
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
String json = sb.toString();
String json is by using DefaultHttpClient
"401 Authorization Required..." but I added Authorization to the Header, didn't I? And it's empty using HttpURLConnection
.
Is it a HTTP problem? A Java problem? An Android problem??? help me please!!