Android应用经常会和服务器端交互,这就需要手机客户端发送网络请求,下面介绍四种常用网络请求方式,我这边是通过Android单元测试来完成这四种方法的,还不清楚Android的单元测试的同学们请看Android开发技巧总结中的Android单元测试的步骤一文。
java.net包中的HttpURLConnection类
Get方式:
[java] view plaincopyprint?
// 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();
}
// 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 plaincopyprint?
// 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方式请求失败");
}
}
// 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 plaincopyprint?
// 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方式请求失败");
}
}
// 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 plaincopyprint?
// HttpPost方式请求
public static void requestByHttpPost() throws Exception {
String path = "https://reg.163.com/logins.jsp";
// 新建HttpPost对象
HttpPost httpPost = new HttpPost(path);
// Post参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
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. PL/SQL 将旧表的一些字段赋值给新的表中的字段的做法
  2. BZOJ4643 : 卡常大水题
  3. 微信公众平台开发接口PHP SDK完整版(转载)
  4. Centos7.2 Systemd 方式编译 Mysql5.7.11
  5. JS模块间错误隔离
  6. c++类中的常量
  7. Populating Display Item Value On Query In Oracle Forms
  8. SCOM随笔
  9. empty 和isset的差别
  10. python基于万象优图识别图片中的中文
  11. Swift3.0 自定义tableView复用cell 的写法,与CollectionViewCell的不同,数据model
  12. BZOJ 3168: [Heoi2013]钙铁锌硒维生素 [线性基 Hungary 矩阵求逆]
  13. CF 375D. Tree and Queries加强版!!!【dfs序分块 大小分类讨论】
  14. [Vue] karme/jasmine/webpack/vue搭建测试环境
  15. Exp6 信息收集与漏洞扫描
  16. 网络请求————ProxyHandler实现代理ip
  17. 章节四、1-if条件语句
  18. CentOS 6.x 最小化安装推荐安装的依赖包和修改内核参数
  19. 用SQL快速删除U8账套
  20. seo:与优化相关的熊掌号

热门文章

  1. Mac OS 终端强化美化:iterm2 + zsh + oh~my~zsh 设置教程
  2. 【cpu】CPU版本认识
  3. python的部分内置函数
  4. 从士兵到程序员再到 SOHO 程序员 (三) - 游击战与阻力
  5. Mac下的Eclipse不能记住工作空间问题
  6. 信息安全试验-DES加密!
  7. 【Luogu】P2704炮兵阵地(状压DP)
  8. BZOJ 2005 [Noi2010]能量采集 ——Dirichlet积
  9. POJ 2154 Color ——Burnside引理
  10. Codeforces 333E Summer Earnings ——Bitset