码迷,mamicode.com
首页 > 移动开发 > 详细

Android 设置代理(验证用户名和密码)

时间:2015-06-29 19:54:41      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

 这几天在研究在Android中,解析网页,但是公司内容,链接外网需要代理,并需要验证用户名和密码,十分头疼,网上查了下,没有头绪,最后总算在一个外国博客中看到类似的,记录下

 

URL url = new URL(urlString);    String host=android.net.Proxy.getDefaultHost();    int port=android.net.Proxy.getDefaultPort();        SocketAddress address=null;    try {     address=new InetSocketAddress(host, port);    } catch (Exception e) {     System.out.println(e.getMessage());    }        Proxy proxy=new java.net.Proxy(java.net.Proxy.Type.HTTP, address);    String credentials = "z10127:scdp@2015";    byte[] toencode = null;    try {        toencode = credentials.getBytes("UTF-8");    } catch (UnsupportedEncodingException e1) {        e1.printStackTrace();    }    HttpURLConnection  ucon=null;        try {     ucon =(HttpURLConnection)url.openConnection(proxy);     ucon.setConnectTimeout(50000) ;

    ucon.setRequestProperty("Proxy-Authorization", "Basic " + Base64.encodeToString(toencode, Base64.DEFAULT));

    //ucon.connect();    } catch (Exception e) {     e.printStackTrace();    }    

   //ucon.connect();     int responseCode = ucon.getResponseCode();     InputStream instr=null;           if(responseCode == HttpURLConnection.HTTP_OK){            instr = ucon.getInputStream();           }    BufferedInputStream bis = new BufferedInputStream(instr);    ByteArrayBuffer baf = new ByteArrayBuffer(1024);    int current = 0;    while ((current = bis.read()) != -1) {     //baf..append(new String(baf,0,current,"UTF-8"));     baf.append((byte) current);    }    instr.close();    bis.close();    ucon.disconnect();    return EncodingUtils.getString(baf.toByteArray(), "gb2312");

Android 设置代理(验证用户名和密码)

标签:

原文地址:http://www.cnblogs.com/Hobin/p/4607833.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!