HttpURLConnection安全认证式访问方法

 在使用http访问网站时,有时候网站需要提供用户名和密码,才能访问到具体内容。我们用代码怎么来填入这些认证信息呢?

    下面是一些具体的代码:

    URL realUrl = new URL(url);

    HttpURLConnection httpUrlConnection = (HttpURLConnection) realUrl.openConnection();        

    httpUrlConnection.setRequestProperty("accept", "*/*");

    httpUrlConnection.setRequestProperty("connection", "Keep-Alive");

    httpUrlConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0;               Windows NT 5.1;SV1)");

    httpUrlConnection.setRequestProperty("content-Type", "text/xml");

    httpUrlConnection.setConnectTimeout(60000);

    //设置用户名和密码

    String user = "www.test.com";

    String pwd = "mysys";

    String auth = user+":"+pwd;

    //对其进行加密

     byte[] rel = Base64.encodeBase64(auth.getBytes());

    String res = new String(rel);

    //设置认证属性

    httpUrlConnection.setRequestProperty("Authorization","Basic " + res);

    httpUrlConnection.setReadTimeout(readTimeout);

    httpUrlConnection.connect();

    Map<String, List<String>> map = httpUrlConnection.getHeaderFields();

猜你喜欢

转载自welcome66.iteye.com/blog/2286241