凡是接触过android应用开发的,都离不开网络编程,android应用作为一个客户端,没有了服务端的服务是没多大作为的,要跟服务端交互,必须要用到网络编程,就我接触来说,android的网络编程有三种方法。

方法一、利用httpurlconnection,用法如下

利用HttpURLConnection对象,我们可以向网络发送请求参数.

String requestUrl = http://localhost:8080/itcast/contanctmanage.do;Map<String, String> requestParams = new HashMap<String, String>();requestParams.put("age", "12");requestParams.put("name", "中国"); StringBuilder params = new StringBuilder();for(Map.Entry<String, String> entry : requestParams.entrySet()){    params.append(entry.getKey());    params.append("=");    params.append(URLEncoder.encode(entry.getValue(), "UTF-8"));    params.append("&");}if (params.length() > 0) params.deleteCharAt(params.length() - 1);byte[] data = params.toString().getBytes();URL realUrl = new URL(requestUrl);HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();conn.setDoOutput(true);//发送POST请求必须设置允许输出conn.setUseCaches(false);//不使用Cacheconn.setRequestMethod("POST");            conn.setRequestProperty("Connection", "Keep-Alive");//维持长连接conn.setRequestProperty("Charset", "UTF-8");conn.setRequestProperty("Content-Length", String.valueOf(data.length));conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());outStream.write(data);outStream.flush
   方法二、利用httpclient,用法如下,传参数
 HttpClient client = new DefaultHttpClient(); //创建一个HttpClient  HttpPost request = new HttpPost(); //实例化新的Http方法 request.setURI(new URI("http://code.google.com/android/")); // 设置HTTP参数 List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuepair("one","valueGoesHere")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); request.setEntity(formEntity); HttpResponse response = client.execute(request);//使用httpClient执行HTTP调用 BufferedReader in = new BufferedReader(new InputSteamReader(response.getEntity.getContent));//处理HTTP响应
   方法三,利用androidhttpclient
  
经过实际项目,利用方法一的时候,第一连接服务器,在connect的时候,要花比较长的时间,
而方法二在连接服务器时,速度比较快,网络好时,3秒就连接上,
强力推荐用方法二,HttpClient。
  
  


更多相关文章

  1. 【Android】使用Gallery组件实现循环显示图像
  2. 阅读Android消息机制源码的随手笔记
  3. 为何GoogleSearch中可以嵌入EditText?
  4. Android(安卓)应用权限管理默认开关的修改方法
  5. Android(安卓)WebView 全面干货指南
  6. 【Android(安卓)界面效果13】关于全屏和取消标题栏
  7. Android面试题(数据存储、view篇)
  8. Android(安卓)Service 介绍
  9. android 自动弹起键盘

随机推荐

  1. android一个很恶心的东西
  2. Android的init过程详解(一)
  3. Android高手进阶教程(十九)---Android中
  4. Android之——史上最简单最酷炫的3D图片
  5. android之sqliteDatabase,sqliteOpenHelp
  6. Android基础入门教程——8.1.1 Android中
  7. 浅谈Android中MVC、MVP、MVVM模式(二)
  8. KJFrameForAndroid(安卓)1.3beta 发布,And
  9. 深刻解析 Android(安卓)的 AIDL 介面
  10. android style(样式)和theme(主题)设置