android之网络编程

 凡是接触过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);//不使用Cache
conn.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。
 
 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值