android网络连接总结

一:HttpURLConnection 

URL sourceUrl; String fileName =""; try { sourceUrl = new URL("网址"); fileName = sourceUrl.getFile(); fileName = fileName.substring(fileName.lastIndexOf('/') + 1); fileName = "/sdcard/"+(new Date()).getTime()+fileName; /*创建临时文件 File myTempFile = File.createTempFile("temfile", "."+"mp3");//文件扩展名 记录临时文件名 currentTempFilePath = myTempFile.getAbsolutePath(); */ FileOutputStream fos = new FileOutputStream(fileName); int read = 0; byte[] buffer = new byte[512]; HttpURLConnection conn = (HttpURLConnection) sourceUrl.openConnection(); conn.setDoInput(true); conn.connect(); int length = conn.getContentLength(); InputStream is = conn.getInputStream(); do{ read = is.read(buffer); if(read > 0){ fos.write(buffer, 0, read); } }while(read != -1); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } if(fileName !=""){ File file = new File(fileName); if (file.exists()){ //根据filename,操作这个文件 } }  

URL imageUrl = null; Bitmap bitmap = null; try { /* new URL对象将网址传入 */ imageUrl = new URL(uriPic); } catch (MalformedURLException e) { e.printStackTrace(); } try { /* 取得连接 */ HttpURLConnection conn = (HttpURLConnection) imageUrl .openConnection(); conn.connect(); /* 取得返回的InputStream */ InputStream is = conn.getInputStream(); mTextView1.setText(conn.getResponseCode()+"="+conn.getResponseMessage()); /* 将InputStream变成Bitmap */ bitmap = BitmapFactory.decodeStream(is); /* 关闭InputStream */ is.close(); } catch (IOException e) { e.printStackTrace(); }  

处理文字数据

/* 将InputStream转成Reader */ BufferedReader in = new BufferedReader(new InputStreamReader( conn.getInputStream())); String inputLine; /* 图文件路径 */ String uriPic = ""; /* 一行一行读取 */ while ((inputLine = in.readLine()) != null) { uriPic += inputLine; }  

 

URLConnection 获取图片

URL aryURI = new URL(myImageURL[position]); URLConnection conn = aryURI.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); Bitmap bm = BitmapFactory.decodeStream(is); is.close(); imageView.setImageBitmap(bm);  

 

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

XML 的应用

URL url = new URL(ConstData.queryString+cityParamString); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); myHandler gwh = new myHandler(); xr.setContentHandler(gwh); InputStreamReader isr =new InputStreamReader(url.openStream(),"GBK"); InputSource is=new InputSource(isr); xr.parse(is);  

 

向服务器上传文件 

private void uploadFile() { String end = "/r/n"; String twoHyphens = "--"; String boundary = "*****"; try { URL url =new URL(actionUrl); HttpURLConnection con=(HttpURLConnection)url.openConnection(); /* 允许Input、Output,不使用Cache */ con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); /* 设置传送的method=POST */ con.setRequestMethod("POST"); /* setRequestProperty */ con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); /* 设置DataOutputStream */ DataOutputStream ds = new DataOutputStream(con.getOutputStream()); ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; " + "name=/"file1/";filename=/"" + newName +"/"" + end); ds.writeBytes(end); /* 取得文件的FileInputStream */ FileInputStream fStream = new FileInputStream(uploadFile); /* 设置每次写入1024bytes */ int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int length = -1; /* 从文件读取数据至缓冲区 */ while((length = fStream.read(buffer)) != -1) { /* 将资料写入DataOutputStream中 */ ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + twoHyphens + end); /* close streams */ fStream.close(); ds.flush(); /* 取得Response内容 */ InputStream is = con.getInputStream(); int ch; StringBuffer b =new StringBuffer(); while( ( ch = is.read() ) != -1 ) { b.append( (char)ch ); } /* 将Response显示于Dialog */ showDialog(b.toString().trim()); /* 关闭DataOutputStream */ ds.close(); } catch(Exception e) { showDialog(""+e); } }  

 

DefaultHttpClient 
用户登录验证 

/* 账号:david */ /* 密码:1234 */ String uriAPI = "http://www.dubblogs.cc:8751/Android/Test/API/TestLogin/index.php"; String strRet = ""; try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse response; HttpPost httpost = new HttpPost(uriAPI); List <NameValuePair> nvps = new ArrayList <NameValuePair>(); nvps.add(new BasicNameValuePair("uid", strUID)); nvps.add(new BasicNameValuePair("upw", strUPW)); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); //entity = response.getEntity(); Log.d(TAG, "HTTP POST getStatusLine: " + response.getStatusLine()); /* HTML POST response BODY */ strRet = EntityUtils.toString(entity); Log.i(TAG, strRet); strRet = strRet.trim().toLowerCase(); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (entity != null) { entity.consumeContent(); } Log.d(TAG, "HTTP POST Initialize of cookies."); cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { Log.d(TAG, "HTTP POST Cookie not found."); Log.i(TAG, entity.toString()); } else { for (int i = 0; i < cookies.size(); i++) { Log.d(TAG, "HTTP POST Found Cookie: " + cookies.get(i).toString()); } } if(strRet.equals("y")) { Log.i("TEST", "YES"); return true; } else { Log.i("TEST", "NO"); return false; } } catch(Exception e) { e.printStackTrace(); return false; }  

 

 

 

你可能感兴趣的:(android网络连接总结)