android网络通信

android提供两种通信方式:HTTP和socket,其中支持HTTP协议的工具类有HttpURLConnection和URL,还有Apache的工具包HTTPClient。HttpURLConnection提供了最基础的HTTP通信方式。而HTTPClient则功能更加强大,提供了对Cookie,SSl,HTTPS的支持。简而言之,HTTPClient相当于PC上浏览器的API封装。而android中的socket何java的socket基本一致。

HTTP协议和Socket协议最大的区别就是Socket是长连接的,而HTTP是短连接的。

下面给出HTTP通信的例子[POST]:

public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception{ StringBuilder sb = new StringBuilder(); /** *组建Post请求方式的请求内容 */ if(params!=null && !params.isEmpty()){ for(Map.Entry<String, String> entry : params.entrySet()){ sb.append(entry.getKey()).append('=') .append(URLEncoder.encode(entry.getValue(), enc)).append('&'); } sb.deleteCharAt(sb.length()-1); } byte[] entitydata = sb.toString().getBytes();//得到实体的二进制数据 URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5 * 1000); //如果通过post提交数据,必须设置允许对外输出数据,设置内容类型,设置内容长度 conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length)); OutputStream outStream = conn.getOutputStream(); outStream.write(entitydata); outStream.flush(); outStream.close(); if(conn.getResponseCode()==200){ return true; } return false; }

下面给出HTTP通信的例子[GET]:

public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception{ /** *组建GET请求方式的请求内容 */ StringBuilder sb = new StringBuilder(path); sb.append('?'); for(Map.Entry<String, String> entry : params.entrySet()){ sb.append(entry.getKey()).append('=') .append(URLEncoder.encode(entry.getValue(), enc)).append('&'); } sb.deleteCharAt(sb.length()-1); URL url = new URL(sb.toString()); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); if(conn.getResponseCode()==200){ return true; } return false; }

下面给出HTTP通信的例子[HTTPClient]:

public static boolean sendRequestFromHttpClient(String path, Map<String, String> params, String enc) throws Exception{ List<NameValuePair> paramPairs = new ArrayList<NameValuePair>(); if(params!=null && !params.isEmpty()){ for(Map.Entry<String, String> entry : params.entrySet()){ paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, enc);//得到经过编码过后的实体数据 HttpPost post = new HttpPost(path); //form post.setEntity(entitydata); DefaultHttpClient client = new DefaultHttpClient(); //浏览器 HttpResponse response = client.execute(post);//执行请求 if(response.getStatusLine().getStatusCode()==200){ return true; } return false; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值