Ref:http://blog.csdn.net/zuolongsnail/article/details/6373051

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

 

java.net包中的HttpURLConnection

 

Get方式:

 

// 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方式:

 

// 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包中的HttpGetHttpPost

 

Get方式:

 

// 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方式:

 

// 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方式请求失败");  

    }  

}  

 

以上是一些部分代码,测试的时候在测试类中运行对应的测试方法即可。

更多相关文章

  1. android google地图定位开发,且可以自由移动位置重新获取定位,地址
  2. android带有文字的图片按钮的两种实现方式
  3. Android应用程序请求SurfaceFlinger服务创建Surface的过程分析
  4. android 添加文件打开方式,找了很久终于找到了,收藏起来吧
  5. Android使用Presentation进行双屏开发
  6. [Android]Android(安卓)Studio获取开发版和发布版的MD5和SHA1
  7. android 笔记 --- 获取Android系统的唯一识别码
  8. Android获取摄像头详细信息
  9. Android--布局方式(LinearLayout)学习

随机推荐

  1. Unity打包Android提示找不到jdk解决方案
  2. Intent小结
  3. 最快Android模拟器Genymotion的安装
  4. android显示通知栏
  5. Android应用程序全屏显示的方法
  6. Error:Execution failed for task ':app:
  7. android HttpClient网络通信工具类基于XM
  8. Android(安卓)Studio 插件--postfix
  9. iOS/Android(安卓)DevCamp:我们只谈移动开
  10. Android屏幕自适应4种解决方案