[转]android网络连接

本文转自:http://dev.10086.cn/cmdn/wiki/index.php?doc-view-3685.html

 

一:HttpURLConnection 
Java代码 
  1. URL sourceUrl;  
  2. String fileName ="";  
  3.           
  4.         try {  
  5.             sourceUrl = new URL("网址");  
  6.             fileName = sourceUrl.getFile();  
  7.             fileName = fileName.substring(fileName.lastIndexOf('/') + 1);             
  8.             fileName = "/sdcard/"+(new Date()).getTime()+fileName;  
  9.              /*创建临时文件 
  10.                 File myTempFile = File.createTempFile("temfile",                                 "."+"mp3");//文件扩展名 
  11.          记录临时文件名 
  12.         currentTempFilePath = myTempFile.getAbsolutePath(); 
  13.               */  
  14.             FileOutputStream fos = new FileOutputStream(fileName);  
  15.             int read = 0;  
  16.             byte[] buffer = new byte[512];  
  17.               
  18.             HttpURLConnection conn = (HttpURLConnection) sourceUrl.openConnection();  
  19.             conn.setDoInput(true);  
  20.             conn.connect();  
  21.             int length = conn.getContentLength();  
  22.               
  23.             InputStream is = conn.getInputStream();  
  24.               
  25.             do{  
  26.                  read = is.read(buffer);  
  27.                  if(read > 0){  
  28.                       fos.write(buffer, 0, read);                      
  29.                  }  
  30.             }while(read != -1);  
  31.               
  32.         } catch (MalformedURLException e) {  
  33.             // TODO Auto-generated catch block  
  34.             e.printStackTrace();              
  35.             return;  
  36.         } catch (IOException e) {  
  37.             // TODO Auto-generated catch block  
  38.             e.printStackTrace();          
  39.             return;  
  40.         }  
  41.         if(fileName !=""){  
  42.             File file = new File(fileName);  
  43.             if (file.exists()){                       
  44.                 //根据filename,操作这个文件  
  45.             }  
  46.         }  

Java代码 
  1. URL imageUrl = null;  
  2.    Bitmap bitmap = null;  
  3.    try  
  4.    {  
  5.      /* new URL对象将网址传入 */  
  6.      imageUrl = new URL(uriPic);  
  7.    }  
  8.    catch (MalformedURLException e)  
  9.    {  
  10.      e.printStackTrace();  
  11.    }  
  12.    try  
  13.    {  
  14.      /* 取得连接 */  
  15.      HttpURLConnection conn = (HttpURLConnection) imageUrl  
  16.          .openConnection();  
  17.      conn.connect();  
  18.      /* 取得返回的InputStream */  
  19.      InputStream is = conn.getInputStream();  
  20.      mTextView1.setText(conn.getResponseCode()+"="+conn.getResponseMessage());  
  21.      /* 将InputStream变成Bitmap */  
  22.      bitmap = BitmapFactory.decodeStream(is);  
  23.      /* 关闭InputStream */  
  24.      is.close();  
  25.    }  
  26.    catch (IOException e)  
  27.    {  
  28.      e.printStackTrace();  
  29.    }  

处理文字数据 
Java代码 
  1. /* 将InputStream转成Reader */  
  2.       BufferedReader in = new BufferedReader(new InputStreamReader(  
  3.           conn.getInputStream()));  
  4.       String inputLine;  
  5.       /* 图文件路径 */  
  6.       String uriPic = "";  
  7.       /* 一行一行读取 */  
  8.       while ((inputLine = in.readLine()) != null)  
  9.       {  
  10.         uriPic += inputLine;  
  11.       }  



URLConnection 获取图片 
Java代码 
  1. URL aryURI = new URL(myImageURL[position]);  
  2.   
  3. URLConnection conn = aryURI.openConnection();  
  4. conn.connect();  
  5.   
  6. InputStream is = conn.getInputStream();  
  7.   
  8. Bitmap bm = BitmapFactory.decodeStream(is);  
  9.   
  10. is.close();  
  11.   
  12. imageView.setImageBitmap(bm);  

注:URL可以直接InputStream is = URL.openStream(); 

XML 的应用 
Java代码 
  1. URL url = new URL(ConstData.queryString+cityParamString);  
  2.                       
  3.                     SAXParserFactory spf = SAXParserFactory.newInstance();   
  4.                     SAXParser sp = spf.newSAXParser();   
  5.   
  6.                       
  7.                     XMLReader xr = sp.getXMLReader();  
  8.                       
  9.                     myHandler gwh = new myHandler();   
  10.                     xr.setContentHandler(gwh);   
  11.   
  12.                     InputStreamReader isr =new InputStreamReader(url.openStream(),"GBK");  
  13.                     InputSource is=new InputSource(isr);  
  14.                       
  15.                     xr.parse(is);  


向服务器上传文件 
Java代码 
  1. private void uploadFile()  
  2.   {  
  3.     String end = "\r\n";  
  4.     String twoHyphens = "--";  
  5.     String boundary = "*****";  
  6.     try  
  7.     {  
  8.       URL url =new URL(actionUrl);  
  9.       HttpURLConnection con=(HttpURLConnection)url.openConnection();  
  10.       /* 允许Input、Output,不使用Cache */  
  11.       con.setDoInput(true);  
  12.       con.setDoOutput(true);  
  13.       con.setUseCaches(false);  
  14.       /* 设置传送的method=POST */  
  15.       con.setRequestMethod("POST");  
  16.       /* setRequestProperty */  
  17.       con.setRequestProperty("Connection""Keep-Alive");  
  18.       con.setRequestProperty("Charset""UTF-8");  
  19.       con.setRequestProperty("Content-Type",  
  20.                          "multipart/form-data;boundary="+boundary);  
  21.       /* 设置DataOutputStream */  
  22.       DataOutputStream ds =   
  23.         new DataOutputStream(con.getOutputStream());  
  24.       ds.writeBytes(twoHyphens + boundary + end);  
  25.       ds.writeBytes("Content-Disposition: form-data; " +  
  26.                     "name=\"file1\";filename=\"" +  
  27.                     newName +"\"" + end);  
  28.       ds.writeBytes(end);     
  29.   
  30.       /* 取得文件的FileInputStream */  
  31.       FileInputStream fStream = new FileInputStream(uploadFile);  
  32.       /* 设置每次写入1024bytes */  
  33.       int bufferSize = 1024;  
  34.       byte[] buffer = new byte[bufferSize];  
  35.   
  36.       int length = -1;  
  37.       /* 从文件读取数据至缓冲区 */  
  38.       while((length = fStream.read(buffer)) != -1)  
  39.       {  
  40.         /* 将资料写入DataOutputStream中 */  
  41.         ds.write(buffer, 0, length);  
  42.       }  
  43.       ds.writeBytes(end);  
  44.       ds.writeBytes(twoHyphens + boundary + twoHyphens + end);  
  45.   
  46.       /* close streams */  
  47.       fStream.close();  
  48.       ds.flush();  
  49.   
  50.       /* 取得Response内容 */  
  51.       InputStream is = con.getInputStream();  
  52.       int ch;  
  53.       StringBuffer b =new StringBuffer();  
  54.       while( ( ch = is.read() ) != -1 )  
  55.       {  
  56.         b.append( (char)ch );  
  57.       }  
  58.       /* 将Response显示于Dialog */  
  59.       showDialog(b.toString().trim());  
  60.       /* 关闭DataOutputStream */  
  61.       ds.close();  
  62.     }  
  63.     catch(Exception e)  
  64.     {  
  65.       showDialog(""+e);  
  66.     }  
  67.   }  

DefaultHttpClient 
用户登录验证 
Java代码 
  1. /* 账号:david */  
  2.    /* 密码:1234 */  
  3.    String uriAPI = "http://www.dubblogs.cc:8751/Android/Test/API/TestLogin/index.php";  
  4.    String strRet = "";  
  5.      
  6.    try  
  7.    {  
  8.      DefaultHttpClient httpclient = new DefaultHttpClient();  
  9.      HttpResponse response;  
  10.      HttpPost httpost = new HttpPost(uriAPI);  
  11.      List <NameValuePair> nvps = new ArrayList <NameValuePair>();  
  12.      nvps.add(new BasicNameValuePair("uid", strUID));   
  13.      nvps.add(new BasicNameValuePair("upw", strUPW));   
  14.        
  15.      httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));  
  16.        
  17.      response = httpclient.execute(httpost);  
  18.      HttpEntity entity = response.getEntity();  
  19.      //entity = response.getEntity();  
  20.        
  21.      Log.d(TAG, "HTTP POST getStatusLine: " + response.getStatusLine());  
  22.        
  23.      /* HTML POST response BODY */  
  24.      strRet = EntityUtils.toString(entity);  
  25.      Log.i(TAG, strRet);  
  26.      strRet = strRet.trim().toLowerCase();  
  27.        
  28.      List<cookie> cookies = httpclient.getCookieStore().getCookies();  
  29.      if (entity != null)  
  30.      {  
  31.        entity.consumeContent();  
  32.      }  
  33.        
  34.      Log.d(TAG, "HTTP POST Initialize of cookies.");   
  35.      cookies = httpclient.getCookieStore().getCookies();   
  36.      if (cookies.isEmpty())  
  37.      {  
  38.        Log.d(TAG, "HTTP POST Cookie not found.");  
  39.        Log.i(TAG, entity.toString());  
  40.      }  
  41.      else  
  42.      {  
  43.        for (int i = 0; i < cookies.size(); i++)  
  44.        {  
  45.          Log.d(TAG, "HTTP POST Found Cookie: " + cookies.get(i).toString());   
  46.        }   
  47.      }  
  48.        
  49.        
  50.      if(strRet.equals("y"))  
  51.      {  
  52.        Log.i("TEST""YES");  
  53.        return true;  
  54.      }  
  55.      else  
  56.      {  
  57.        Log.i("TEST""NO");  
  58.        return false;  
  59.      }  
  60.    }  
  61.    catch(Exception e)  
  62.    {  
  63.      e.printStackTrace();  
  64.      return false;  
  65.    }  

 

posted on 2011-12-28 15:56  freeliver54  阅读(500)  评论(0编辑  收藏  举报

导航