最近做了一段时间android网络编程方面的项目,现在总结一下android中网络连接方式,

android中网络通信分为socket编程和http编程,这里只介绍htt方面。网络请求方式可分为get请求,post两种请求方式,GET方式在进行数据请求时,会把数据附加到URL后面传递给服务器,比如常见的:http://XXX.XXX.XXX/XX.aspx?id=1,POST方式则是将请求的数据放到HTTP请求头中,作为请求头的一部分传入服务器。
所以,在进行HTTP编程前,首先要明确究竟使用的哪种方式进行数据请求的。

android中Http编程有两种:1、HttpURLConnection;2、HttpClient


首先介绍一下HttpURLConnection方式的get请求和post请求方法:


private Map<String, String> paramsValue;String urlPath=null;// 发送地http://192.168.100.91:8080/myweb/login?username=abc&password=123public void initData(){urlPath="http://192.168.100.91:8080/myweb/login";paramsValue=new HashMap<String, String>();paramsValue.put("username", "111");paramsValue.put("password", "222"); }

get方式发起请求:

private boolean sendGETRequest(String path, Map<String, String> params) throws Exception {boolean success=false; // StringBuilder是用来组拼请求地址和参数StringBuilder sb = new StringBuilder();sb.append(path).append("?");if (params != null && params.size() != 0) {for (Map.Entry<String, String> entry : params.entrySet()) {// 如果请求参数中有中文,需要进行URLEncoder编码 gbk/utf8sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));sb.append("&");}sb.deleteCharAt(sb.length() - 1);}URL url = new URL(sb.toString());HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(20000);conn.setRequestMethod("GET");if (conn.getResponseCode() == 200) {success= true;}if(conn!=null)conn.disconnect();return success;}


postt方式发起请求:

private boolean sendPOSTRequest(String path,Map<String, String> params) throws Exception{boolean success=false; //StringBuilder是用来组拼请求参数StringBuilder sb = new StringBuilder();if(params!=null &¶ms.size()!=0){            for (Map.Entry<String, String> entry : params.entrySet()) {                   sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));                   sb.append("&");                                      }            sb.deleteCharAt(sb.length()-1);}//entity为请求体部分内容//如果有中文则以UTF-8编码为username=%E4%B8%AD%E5%9B%BD&password=123byte[] entity = sb.toString().getBytes(); URL url = new URL(path);     HttpURLConnection conn = (HttpURLConnection) url.openConnection();     conn.setConnectTimeout(2000);     // 设置以POST方式       conn.setRequestMethod("POST");    // Post 请求不能使用缓存          //  urlConn.setUseCaches(false);      //要向外输出数据,要设置这个     conn.setDoOutput(true);     // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded         //设置content-type获得输出流,便于想服务器发送信息。    //POST请求这个一定要设置     conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");     conn.setRequestProperty("Content-Length", entity.length+"");  // 要注意的是connection.getOutputStream会隐含的进行connect。      OutputStream out = conn.getOutputStream();     //写入参数值     out.write(entity);    //刷新、关闭           out.flush();           out.close();     if (conn.getResponseCode() == 200) {success= true;}     if(conn!=null)conn.disconnect();return success; }

在介绍一下HttpClient方式,相比HttpURLConnection,HttpClient封装的得更简单易用一些,看一下实例:

get方式发起请求:

public String getRequest(String UrlPath,Map<String, String> params){String content=null;StringBuilder buf = new StringBuilder();if(params!=null &¶ms.size()!=0){            for (Map.Entry<String, String> entry : params.entrySet()) {            buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8"));            buf.append("&");                                      }            buf.deleteCharAt(buf.length()-1);}content= buf.toString();HttpClient httpClient = new DefaultHttpClient();HttpGet getMethod = new HttpGet(content);HttpResponse response = null;try {response = httpClient.execute(getMethod);} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}catch (Exception e) {e.printStackTrace();} if (response!=null&&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try {content = EntityUtils.toString(response.getEntity());} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} return content;}

postt方式发起请求:

private boolean sendPOSTRequestHttpClient(String path,Map<String, String> params) throws Exception {boolean success = false;// 封装请求参数List<NameValuePair> pair = new ArrayList<NameValuePair>();if (params != null && !params.isEmpty()) {for (Map.Entry<String, String> entry : params.entrySet()) {pair.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}}// 把请求参数变成请求体部分UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");// 使用HttpPost对象设置发送的URL路径HttpPost post = new HttpPost(path);// 发送请求体post.setEntity(uee);// 创建一个浏览器对象,以把POST对象向服务器发送,并返回响应消息DefaultHttpClient dhc = new DefaultHttpClient();HttpResponse response = dhc.execute(post);if (response.getStatusLine().getStatusCode() == 200) {success = true;}return success;}


android网络交互还是很重要的,还是值得研究的,ok,好了就先写到这里了。



更多相关文章

  1. Android:你要的WebView与 JS 交互方式 都在这里了
  2. [Android] 利用java反射调用隐藏Api
  3. 安卓基础知识总结
  4. Android项目总结5
  5. android开发的3种方式
  6. Android(安卓)数据存储五种方式使用与总结
  7. Android逆向之旅---Hook神器家族的Frida工具使用详解
  8. mybatisplus的坑 insert标签insert into select无参数问题的解决
  9. Python技巧匿名函数、回调函数和高阶函数

随机推荐

  1. Android虚拟sdcard
  2. Android学习之通过content provider获得
  3. API 25 (Android(安卓)7.1.1 API) widget
  4. Android样式设计
  5. 彻底解决Android中文乱码
  6. android刮刮乐
  7. AndroidManifest.xml文件详解(supports-sc
  8. viewFlipper 之二
  9. Android(安卓)与 native C 利用本地socke
  10. Android(安卓)Studio 导入问题总结-IT蓝