这几天在研究在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");

posted on 2015-06-29 16:44  Hobin  阅读(1886)  评论(2编辑  收藏  举报