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

 这几天在研究在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 = "用户名:密码";  

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

转载于:https://www.cnblogs.com/Hobin/p/4607833.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值