0

我需要使用 httpclient 连接到运行受 .htaccess 身份验证保护的 PHP 脚本的网页(Apache)。

我已经阅读了一个小时的问题和答案(在这里和其他地方),但没有一个对我有用。人们在 Base64.java 等类中使用的方法不存在,或者参数错误。

我正在连接到正常(像这样的不受保护的网页):

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
nameValuePairs.add(new BasicNameValuePair("date", cDate));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

但是,当页面受到保护时,这自然无济于事。那么我怎样才能以最简单的方式将我的用户名和密码传递给连接呢?

4

1 回答 1

0

您可以在这里获得 Base64:http: //iharder.sourceforge.net/current/java/base64/

我通常会执行以下操作来进行身份验证:

            StringBuilder authentication = new StringBuilder().append("dogT4g").append(":").append("petTheDog5");
            String result = Base64.encodeBytes(authentication.toString().getBytes());
            httppost.setHeader("Authorization", "Basic " + result);

希望能解决您的问题。

于 2012-08-13T13:44:13.277 回答