一、前言

回忆到上篇 《Xamarin.Android再体验之简单的登录Demo》 做登录时,用的是GET的请求,还用的是同步,

于是现在将其简单的改写,做了个简单的封装,包含基于HttpClient和HttpWebRequest两种方式的封装。

由于对这一块还不是很熟悉,所以可能不是很严谨。

二、先上封装好的代码

 using System;
using System.Collections.Generic;
using System.IO;
using System.Json;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks; namespace Catcher.AndroidDemo.Common
{
public static class EasyWebRequest
{
/// <summary>
/// send the post request based on HttpClient
/// </summary>
/// <param name="requestUrl">the url you post</param>
/// <param name="routeParameters">the parameters you post</param>
/// <returns>return a response object</returns>
public static async Task<object> SendPostRequestBasedOnHttpClient(string requestUrl, IDictionary<string, string> routeParameters)
{
object returnValue = new object();
HttpClient client = new HttpClient();
client.MaxResponseContentBufferSize = ;
Uri uri = new Uri(requestUrl);
var content = new FormUrlEncodedContent(routeParameters);
try
{
var response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
var stringValue = await response.Content.ReadAsStringAsync();
returnValue = JsonObject.Parse(stringValue);
}
}
catch (Exception ex)
{
throw ex;
}
return returnValue;
} /// <summary>
/// send the get request based on HttpClient
/// </summary>
/// <param name="requestUrl">the url you post</param>
/// <param name="routeParameters">the parameters you post</param>
/// <returns>return a response object</returns>
public static async Task<object> SendGetRequestBasedOnHttpClient(string requestUrl, IDictionary<string, string> routeParameters)
{
object returnValue = new object();
HttpClient client = new HttpClient();
client.MaxResponseContentBufferSize = ;
//format the url paramters
string paramters = string.Join("&", routeParameters.Select(p => p.Key + "=" + p.Value));
Uri uri = new Uri(string.Format("{0}?{1}", requestUrl, paramters));
try
{
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var stringValue = await response.Content.ReadAsStringAsync();
returnValue = JsonObject.Parse(stringValue);
}
}
catch (Exception ex)
{
throw ex;
}
return returnValue;
} /// <summary>
/// send the get request based on HttpWebRequest
/// </summary>
/// <param name="requestUrl">the url you post</param>
/// <param name="routeParameters">the parameters you post</param>
/// <returns>return a response object</returns>
public static async Task<object> SendGetHttpRequestBaseOnHttpWebRequest(string requestUrl, IDictionary<string, string> routeParameters)
{
object returnValue = new object();
string paramters = string.Join("&", routeParameters.Select(p => p.Key + "=" + p.Value));
Uri uri = new Uri(string.Format("{0}?{1}", requestUrl, paramters));
var request = (HttpWebRequest)HttpWebRequest.Create(uri); using (var response = request.GetResponseAsync().Result as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string stringValue = await reader.ReadToEndAsync();
returnValue = JsonObject.Parse(stringValue);
}
}
}
}
return returnValue;
} /// <summary>
/// send the post request based on httpwebrequest
/// </summary>
/// <param name="url">the url you post</param>
/// <param name="routeParameters">the parameters you post</param>
/// <returns>return a response object</returns>
public static async Task<object> SendPostHttpRequestBaseOnHttpWebRequest(string url, IDictionary<string, string> routeParameters)
{
object returnValue = new object(); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST"; byte[] postBytes = null;
request.ContentType = "application/x-www-form-urlencoded";
string paramters = string.Join("&", routeParameters.Select(p => p.Key + "=" + p.Value));
postBytes = Encoding.UTF8.GetBytes(paramters.ToString()); using (Stream outstream = request.GetRequestStreamAsync().Result)
{
outstream.Write(postBytes, , postBytes.Length);
} using (HttpWebResponse response = request.GetResponseAsync().Result as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string stringValue = await reader.ReadToEndAsync();
returnValue = JsonObject.Parse(stringValue);
}
}
}
}
return returnValue;
}
}
}

需要说明一下的是,我把这个方法当做一个公共方法抽离到一个单独的类库中

三、添加两个数据服务的方法

         [HttpPost]
public ActionResult PostThing(string str)
{
var json = new
{
Code ="",
Msg = "OK",
Val = str
};
return Json(json);
} public ActionResult GetThing(string str)
{
var json = new
{
Code = "",
Msg = "OK",
Val = str
};
return Json(json,JsonRequestBehavior.AllowGet);
}

这两个方法,一个是为了演示post,一个是为了演示get

部署在本地的IIS上便于测试!

四、添加一个Android项目,测试我们的方法

先来看看页面,一个输入框,四个按钮,这四个按钮分别对应一种请求。

然后是具体的Activity代码

 using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using Catcher.AndroidDemo.Common;
using System.Json; namespace Catcher.AndroidDemo.EasyRequestDemo
{
[Activity(Label = "简单的网络请求Demo", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
EditText txtInput;
Button btnPost;
Button btnGet;
Button btnPostHWR;
Button btnGetHWR;
TextView tv; protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle); SetContentView(Resource.Layout.Main); txtInput = FindViewById<EditText>(Resource.Id.txt_input);
btnPost = FindViewById<Button>(Resource.Id.btn_post);
btnGet = FindViewById<Button>(Resource.Id.btn_get);
btnGetHWR = FindViewById<Button>(Resource.Id.btn_getHWR);
btnPostHWR = FindViewById<Button>(Resource.Id.btn_postHWR);
tv = FindViewById<TextView>(Resource.Id.tv_result); //based on httpclient
btnPost.Click += PostRequest;
btnGet.Click += GetRequest;
//based on httpwebrequest
btnPostHWR.Click += PostRequestByHWR;
btnGetHWR.Click += GetRequestByHWR;
} private async void GetRequestByHWR(object sender, EventArgs e)
{
string url = "http://192.168.1.102:8077/User/GetThing";
IDictionary<string, string> routeParames = new Dictionary<string, string>();
routeParames.Add("str", this.txtInput.Text);
var result = await EasyWebRequest.SendGetHttpRequestBaseOnHttpWebRequest(url, routeParames);
var data = (JsonObject)result;
this.tv.Text = "hey," + data["Val"] + ", i am from httpwebrequest get";
} private async void PostRequestByHWR(object sender, EventArgs e)
{
string url = "http://192.168.1.102:8077/User/PostThing";
IDictionary<string, string> routeParames = new Dictionary<string, string>();
routeParames.Add("str", this.txtInput.Text);
var result = await EasyWebRequest.SendPostHttpRequestBaseOnHttpWebRequest(url, routeParames);
var data = (JsonObject)result;
this.tv.Text = "hey," + data["Val"] + ", i am from httpwebrequest post";
} private async void PostRequest(object sender, EventArgs e)
{
string url = "http://192.168.1.102:8077/User/PostThing";
IDictionary<string, string> routeParames = new Dictionary<string, string>();
routeParames.Add("str", this.txtInput.Text);
var result = await EasyWebRequest.SendPostRequestBasedOnHttpClient(url, routeParames);
var data = (JsonObject)result;
this.tv.Text = "hey," + data["Val"] + ", i am from httpclient post";
} private async void GetRequest(object sender, EventArgs e)
{
string url = "http://192.168.1.102:8077/User/GetThing";
IDictionary<string, string> routeParames = new Dictionary<string, string>();
routeParames.Add("str", this.txtInput.Text);
var result = await EasyWebRequest.SendGetRequestBasedOnHttpClient(url, routeParames);
var data = (JsonObject)result;
this.tv.Text = "hey," + data["Val"] + ", i am from httpclient get";
}
}
}

OK,下面看看效果图

      

如果那位大哥知道有比较好用的开源网络框架推荐请告诉我!!

最后放上本次示例的代码:

https://github.com/hwqdt/Demos/tree/master/src/Catcher.AndroidDemo

Xamarin.Android之封装个简单的网络请求类的更多相关文章

  1. Android之封装好的异步网络请求框架

    1.简介  Android中网络请求一般使用Apache HTTP Client或者采用HttpURLConnection,但是直接使用这两个类库需要写大量的代码才能完成网络post和get请求,而使 ...

  2. Android 最早使用的简单的网络请求

    下面是最早从事android开发的时候写的网络请求的代码,简单高效,对于理解http请求有帮助.直接上代码,不用解释,因为非常简单. import java.io.BufferedReader; im ...

  3. 基于Volley,Gson封装支持JWT无状态安全验证和数据防篡改的GsonRequest网络请求类

    这段时间做新的Android项目的client和和REST API通讯框架架构设计.使用了非常多新技术,终于的方案也相当简洁优雅.client仅仅须要传Java对象,server端返回json字符串, ...

  4. block传值以及利用block封装一个网络请求类

    1.block在俩个UIViewController间传值 近期刚学了几招block 的高级使用方法,事实上就是利用block语法在俩个UIViewController之间传值,在这里分享给刚開始学习 ...

  5. Xamarin.Android再体验之简单的登录Demo

    一.前言 在空闲之余,学学新东西 二.服务端的代码编写与部署 这里采取的方式是MVC+EF返回Json数据,(本来是想用Nancy来实现的,想想电脑太卡就不开多个虚拟机了,用用IIS部署也好) 主要是 ...

  6. android 项目中使用到的网络请求框架以及怎样配置好接口URL

    我们在做项目中一定少不了网络请求,如今非常多公司的网络请求这块好多都是使用一些比較好的开源框架,我项目中使用的是volley,如今讲讲一些volley主要的使用,假设想要具体的了解就要去看它的源代码了 ...

  7. 转:Android开源项目推荐之「网络请求哪家强」 Android开源项目推荐之「网络请求哪家强」

    转载自https://zhuanlan.zhihu.com/p/21879931 1. 原则 本篇说的网络请求专指 http 请求,在选择一个框架之前,我个人有个习惯,就是我喜欢选择专注的库,其实在软 ...

  8. android开发学习 ------- Retrofit+Rxjava+MVP网络请求的实例

    http://www.jianshu.com/p/7b839b7c5884   推荐 ,照着这个敲完 , 测试成功 , 推荐大家都去看一下 . 下面贴一下我照着这个敲完的代码: Book实体类 - 用 ...

  9. ios中封装网络请求类

    #import "JSNetWork.h" //asiHttpRequest #import "ASIFormDataRequest.h" //xml 的解析 ...

随机推荐

  1. org.apache.jasper.JasperException:省略"/html/sysmaintain/authority/user/../../module/verify_login.jsp" not found

    说明了JSP页面里引用安全登录页面的jsp路径代码:<%@ include file="../../module/verify_login.jsp"%>这句代码引用的路 ...

  2. ORACLE冷备份与恢复

    ORACLE备份和恢复有三种方式: (1)数据泵(expdp/impdp) (2)冷备份 (3)RMAN备份 就分类而言,(1)和(2)统有称为"冷"备份,(3)称为"热 ...

  3. [译] 理解PHP内部函数的定义(给PHP开发者的PHP源码-第二部分)

    文章来自:http://www.hoohack.me/2016/02/10/understanding-phps-internal-function-definitions-ch 原文:https:/ ...

  4. HTML和CSS经典布局5

    如下图: 需求: 1. 如图 2. 可以从body标签开始. 3. 页面内容高度设置高点,把窗口的滚动条显示出来,但是busy indicator不滚动. <!DOCTYPE html> ...

  5. VS2013的 Browser Link 引起的问题

    环境:vs2013 问题:在调用一个WebApi的时候出现了错误: 于是我用Fiddler 4直接调用这个WebApi,状态码是200(正常的),JSon里却提示在位置9409处文本非法, 以Text ...

  6. 记一个简单的保护if 的sh脚本

    真是坑爹,就下面的sh,竟然也写了很久! if [ `pwd` != '/usr/xx/bin/tomcat' ] then echo "rstall is not allowed in c ...

  7. spring4mvc返回json(bean,list,map)

    因为spring3和spring4的mvc在前端返回json所需要的jar包不一样,所以索性写一篇关于spring4mvc在前端返回json的博文. 首先,新建一个web项目,项目格式如图所示: co ...

  8. MongoDB 分片管理

    在MongoDB(版本 3.2.9)中,分片集群(sharded cluster)是一种水平扩展数据库系统性能的方法,能够将数据集分布式存储在不同的分片(shard)上,每个分片只保存数据集的一部分, ...

  9. 解密jQuery内核 DOM操作的核心buildFragment

    文档碎片是什么 http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-B63ED1A3 DocumentFragment is a & ...

  10. MVC4做网站后台:栏目管理3、删除栏目与左侧列表菜单

    一.左侧列表菜单 打开视图Menu.cshtml,增加部分见红框 在category中添加脚本 //栏目菜单加载完毕函数 function CategoryMenu_Ready() { $('#cat ...