Android应用经常会和服务器端交互,这就需要手机客户端发送网络请求,下面介绍四种常用网络请求方式,我这边是通过Android单元测试来完成这四种方法的,还不清楚Android的单元测试的同学们请看Android开发技巧总结中的Android单元测试的步骤一文。

java.net包中的HttpURLConnection类

Get方式:

[java] view plain copy print ?
  1. // Get方式请求   
  2. public static void requestByGet() throws Exception {  
  3.     String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";  
  4.     // 新建一个URL对象   
  5.     URL url = new URL(path);  
  6.     // 打开一个HttpURLConnection连接   
  7.     HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  8.     // 设置连接超时时间   
  9.     urlConn.setConnectTimeout(5 * 1000);  
  10.     // 开始连接   
  11.     urlConn.connect();  
  12.     // 判断请求是否成功   
  13.     if (urlConn.getResponseCode() == HTTP_200) {  
  14.         // 获取返回的数据   
  15.         byte[] data = readStream(urlConn.getInputStream());  
  16.         Log.i(TAG_GET, "Get方式请求成功,返回数据如下:");  
  17.         Log.i(TAG_GET, new String(data, "UTF-8"));  
  18.     } else {  
  19.         Log.i(TAG_GET, "Get方式请求失败");  
  20.     }  
  21.     // 关闭连接   
  22.     urlConn.disconnect();  
  23. }  
// Get方式请求 public static void requestByGet() throws Exception { String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android"; // 新建一个URL对象 URL url = new URL(path); // 打开一个HttpURLConnection连接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 设置连接超时时间 urlConn.setConnectTimeout(5 * 1000); // 开始连接 urlConn.connect(); // 判断请求是否成功 if (urlConn.getResponseCode() == HTTP_200) { // 获取返回的数据 byte[] data = readStream(urlConn.getInputStream()); Log.i(TAG_GET, "Get方式请求成功,返回数据如下:"); Log.i(TAG_GET, new String(data, "UTF-8")); } else { Log.i(TAG_GET, "Get方式请求失败"); } // 关闭连接 urlConn.disconnect(); }

Post方式:

[java] view plain copy print ?
  1. // Post方式请求   
  2. public static void requestByPost() throws Throwable {  
  3.     String path = "https://reg.163.com/logins.jsp";  
  4.     // 请求的参数转换为byte数组   
  5.     String params = "id=" + URLEncoder.encode("helloworld""UTF-8")  
  6.             + "&pwd=" + URLEncoder.encode("android""UTF-8");  
  7.     byte[] postData = params.getBytes();  
  8.     // 新建一个URL对象   
  9.     URL url = new URL(path);  
  10.     // 打开一个HttpURLConnection连接   
  11.     HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  12.     // 设置连接超时时间   
  13.     urlConn.setConnectTimeout(5 * 1000);  
  14.     // Post请求必须设置允许输出   
  15.     urlConn.setDoOutput(true);  
  16.     // Post请求不能使用缓存   
  17.     urlConn.setUseCaches(false);  
  18.     // 设置为Post请求   
  19.     urlConn.setRequestMethod("POST");  
  20.     urlConn.setInstanceFollowRedirects(true);  
  21.     // 配置请求Content-Type   
  22.     urlConn.setRequestProperty("Content-Type",  
  23.             "application/x-www-form-urlencode");  
  24.     // 开始连接   
  25.     urlConn.connect();  
  26.     // 发送请求参数   
  27.     DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());  
  28.     dos.write(postData);  
  29.     dos.flush();  
  30.     dos.close();  
  31.     // 判断请求是否成功   
  32.     if (urlConn.getResponseCode() == HTTP_200) {  
  33.         // 获取返回的数据   
  34.         byte[] data = readStream(urlConn.getInputStream());  
  35.         Log.i(TAG_POST, "Post请求方式成功,返回数据如下:");  
  36.         Log.i(TAG_POST, new String(data, "UTF-8"));  
  37.     } else {  
  38.         Log.i(TAG_POST, "Post方式请求失败");  
  39.     }  
  40. }  
// Post方式请求 public static void requestByPost() throws Throwable { String path = "https://reg.163.com/logins.jsp"; // 请求的参数转换为byte数组 String params = "id=" + URLEncoder.encode("helloworld", "UTF-8") + "&pwd=" + URLEncoder.encode("android", "UTF-8"); byte[] postData = params.getBytes(); // 新建一个URL对象 URL url = new URL(path); // 打开一个HttpURLConnection连接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 设置连接超时时间 urlConn.setConnectTimeout(5 * 1000); // Post请求必须设置允许输出 urlConn.setDoOutput(true); // Post请求不能使用缓存 urlConn.setUseCaches(false); // 设置为Post请求 urlConn.setRequestMethod("POST"); urlConn.setInstanceFollowRedirects(true); // 配置请求Content-Type urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencode"); // 开始连接 urlConn.connect(); // 发送请求参数 DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream()); dos.write(postData); dos.flush(); dos.close(); // 判断请求是否成功 if (urlConn.getResponseCode() == HTTP_200) { // 获取返回的数据 byte[] data = readStream(urlConn.getInputStream()); Log.i(TAG_POST, "Post请求方式成功,返回数据如下:"); Log.i(TAG_POST, new String(data, "UTF-8")); } else { Log.i(TAG_POST, "Post方式请求失败"); } }  

org.apache.http包中的HttpGet和HttpPost类

Get方式:

[java] view plain copy print ?
  1. // HttpGet方式请求   
  2. public static void requestByHttpGet() throws Exception {  
  3.     String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";  
  4.     // 新建HttpGet对象   
  5.     HttpGet httpGet = new HttpGet(path);  
  6.     // 获取HttpClient对象   
  7.     HttpClient httpClient = new DefaultHttpClient();  
  8.     // 获取HttpResponse实例   
  9.     HttpResponse httpResp = httpClient.execute(httpGet);  
  10.     // 判断是够请求成功   
  11.     if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {  
  12.         // 获取返回的数据   
  13.         String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");  
  14.         Log.i(TAG_HTTPGET, "HttpGet方式请求成功,返回数据如下:");  
  15.         Log.i(TAG_HTTPGET, result);  
  16.     } else {  
  17.         Log.i(TAG_HTTPGET, "HttpGet方式请求失败");  
  18.     }  
  19. }  
// HttpGet方式请求 public static void requestByHttpGet() throws Exception { String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android"; // 新建HttpGet对象 HttpGet httpGet = new HttpGet(path); // 获取HttpClient对象 HttpClient httpClient = new DefaultHttpClient(); // 获取HttpResponse实例 HttpResponse httpResp = httpClient.execute(httpGet); // 判断是够请求成功 if (httpResp.getStatusLine().getStatusCode() == HTTP_200) { // 获取返回的数据 String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8"); Log.i(TAG_HTTPGET, "HttpGet方式请求成功,返回数据如下:"); Log.i(TAG_HTTPGET, result); } else { Log.i(TAG_HTTPGET, "HttpGet方式请求失败"); } }

Post方式:

[java] view plain copy print ?
  1. // HttpPost方式请求   
  2. public static void requestByHttpPost() throws Exception {  
  3.     String path = "https://reg.163.com/logins.jsp";  
  4.     // 新建HttpPost对象   
  5.     HttpPost httpPost = new HttpPost(path);  
  6.     // Post参数   
  7.     List params = new ArrayList();  
  8.     params.add(new BasicNameValuePair("id""helloworld"));  
  9.     params.add(new BasicNameValuePair("pwd""android"));  
  10.     // 设置字符集   
  11.     HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);  
  12.     // 设置参数实体   
  13.     httpPost.setEntity(entity);  
  14.     // 获取HttpClient对象   
  15.     HttpClient httpClient = new DefaultHttpClient();  
  16.     // 获取HttpResponse实例   
  17.     HttpResponse httpResp = httpClient.execute(httpPost);  
  18.     // 判断是够请求成功   
  19.     if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {  
  20.         // 获取返回的数据   
  21.         String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");  
  22.         Log.i(TAG_HTTPGET, "HttpPost方式请求成功,返回数据如下:");  
  23.         Log.i(TAG_HTTPGET, result);  
  24.     } else {  
  25.         Log.i(TAG_HTTPGET, "HttpPost方式请求失败");  
  26.     }  
  27. }  
// HttpPost方式请求 public static void requestByHttpPost() throws Exception { String path = "https://reg.163.com/logins.jsp"; // 新建HttpPost对象 HttpPost httpPost = new HttpPost(path); // Post参数 List params = new ArrayList(); params.add(new BasicNameValuePair("id", "helloworld")); params.add(new BasicNameValuePair("pwd", "android")); // 设置字符集 HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); // 设置参数实体 httpPost.setEntity(entity); // 获取HttpClient对象 HttpClient httpClient = new DefaultHttpClient(); // 获取HttpResponse实例 HttpResponse httpResp = httpClient.execute(httpPost); // 判断是够请求成功 if (httpResp.getStatusLine().getStatusCode() == HTTP_200) { // 获取返回的数据 String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8"); Log.i(TAG_HTTPGET, "HttpPost方式请求成功,返回数据如下:"); Log.i(TAG_HTTPGET, result); } else { Log.i(TAG_HTTPGET, "HttpPost方式请求失败"); } }

 

文章出处:http://blog.csdn.net/zuolongsnail/article/details/6373051

 

更多相关文章

  1. Android定时任务实现方式归纳总结
  2. android v7兼容包RecyclerView的使用(四)——点击事件的不同方式处
  3. Android中的几种网络请求方式详解 .
  4. 初学者---Android(安卓)Fragment之间数据传递的三种方式
  5. android控件的对齐方式转讲
  6. Android(安卓)获取USB扫描枪简易封装
  7. android:launchMode="singleTask" intent获取到的值没有更新
  8. Android(安卓)获取汉字拼音
  9. Android单选框基本应用方式

随机推荐

  1. [Android] SQLite数据库之增删改查基础操
  2. RecyclerView中ViewHolder重用机制理解(
  3. Android将应用程序指定默认语言
  4. Android(安卓)APP 设计说明书模板
  5. 【Android】_音乐列表_仿网易云音乐播放
  6. 为Android添加底层核心服务
  7. 从最简单的Android(安卓)MVP讲起
  8. Android(安卓)Studio中NDK的配置
  9. 关于Android的线程问题
  10. Android(安卓)ORM 框架之 greenDAO