Android开发中的几种网络请求方式详解

时间:2021-05-20

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

Java.NET包中的HttpURLConnection类

Get方式:

// Get方式请求 public static void requestByGet() throws Exception { String path = "https:///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:///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-ameValuePair("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方式请求失败"); } }

以上是一些部分代码,测试的时候在测试类中运行对应的测试方法即可。完整代码点这里下载:源码下载

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章