您可以使用
Authenticator。例如:
Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( "user", "password".toCharArray()); }});这将设置默认值
Authenticator,并将在 所有
请求中使用。显然,当您不需要所有请求的凭据或多个不同的凭据(可能在不同的线程上)时,就需要更多的设置。
或者,您可以使用
DefaultHttpClient带有基本HTTP身份验证的GET请求看起来类似于以下位置的:
HttpClient httpClient = new DefaultHttpClient();HttpGet httpGet = new HttpGet("http://foo.com/bar");httpGet.addHeader(BasicScheme.authenticate( new UsernamePasswordCredentials("user", "password"), "UTF-8", false));HttpResponse httpResponse = httpClient.execute(httpGet);HttpEntity responseEntity = httpResponse.getEntity();// read the stream returned by responseEntity.getContent()我建议使用后者,因为它可以让您对请求进行更多控制(例如,方法,标头,超时等)。



