HttpURLConnection请求

来源:互联网 发布:淘宝发货没有无需物流 编辑:程序博客网 时间:2024/05/16 02:18

//  HttpURLCONnection+Thread+handler


public void qingQiu(final String path,final Handler handler){
        
        new Thread(){
            
            public void run() {
                
                
                 try {
                     URL url=new URL(path);
                     //HttpURLCONnection get请求数据
                     HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
                     
                     openConnection.setReadTimeout(5000);
                     openConnection.setConnectTimeout(5000);
                    openConnection.setRequestMethod("GET");
                    
                    
                     openConnection.connect(); //连接
                     
                     int responseCode = openConnection.getResponseCode();
                     if(responseCode==200){
                         InputStream inputStream = openConnection.getInputStream();
                         String json = streamTo(inputStream);
                         Message msg=Message.obtain();
                         msg.what=1;
                         msg.obj=json;
                         handler.sendMessage(msg);
                         
                    
                     }
                    
                    
                    
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
                
                
            };
            
            
            
        }.start();
        
        
    }
    
    
        
        
        
           //输入流
        public String streamTo(InputStream input){
            
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            byte[] by=new byte[1024];
            int len=0;
            try {
                while((len=input.read(by))!=-1){
                    baos.write(by, 0, len);
                }
                System.out.println("streamto=="+baos.toString());
                return baos.toString();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            
            return null;
        }
0 0
原创粉丝点击