1

我想从具有 Android 上的 http 身份验证的网络服务器下载 html 和 json 文件的内容。在浏览器上,我总是使用http://username:passwort@example.com/path/to/something,效果很好。但是在 Android 上的 Java 中它不起作用(在添加 HTTP 授权之前它运行良好)。我可以使用这个在 webview 中显示一个 html 文件。但是如何下载内容?我总是得到FileNotFoundException。下载html文件的代码:

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();

我尝试下载 json 文件的另一种方法:

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();

或使用 DefaultHttpClient 而不是 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();

最后我想阅读内容:

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();

字符串 json 是通过使用DefaultHttpClient“需要 401 授权...”但我在标题中添加了授权,不是吗?使用它是空的HttpURLConnection

是 HTTP 问题吗?一个Java问题?安卓问题???请帮帮我!!

4

0 回答 0