android网络连接总结
来源:互联网 发布:英国研究生申请 知乎 编辑:程序博客网 时间:2024/05/16 05:07
一: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网络连接总结
- android网络连接总结
- android网络连接总结
- android网络连接总结
- android网络连接总结
- android网络连接总结
- android 网络连接总结
- Android项目技术总结:网络连接总结
- Android项目技术总结:网络连接总结
- Android网络连接网络
- Android网络连接网络
- IOS 网络连接 总结
- android中检测网络连接状态简单总结
- android中检测网络连接状态简单总结
- android中检测网络连接状态简单总结
- 4.2.2.6 android中检测网络连接状态简单总结
- Android网络连接----使用HttpClient连接网络
- Android 网络连接处理
- android 自定义title样式
- android界面无标题栏和全屏效果的实现方式
- Android 按钮效果的两种实现方法
- Android 中的ListView内容刷新问题
- android输入框被键盘遮挡
- android网络连接总结
- Android Nine Patch图片及按钮背景
- android NinePatch使用教程--创建优美的背景图片
- LinearLayout中的layout_weight属性
- container_of()
- android:theme
- android:shape的使用
- qemu调试cortex m3程序
- Java JSplitPane_1