一、前言

回忆到上篇 《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. 译文---C#堆VS栈(Part One)

    前言 本文主要是讲解C#语言在内存中堆.栈的使用情况,使读者能更好的理解值类型.引用类型以及线程栈.托管堆. 首先感谢原文作者:Matthew Cochran 为我们带来了一篇非常好的文章,并配以大量 ...

  2. 老司机学新平台 - Xamarin开发之我的第一个MvvmCross跨平台插件:SimpleAudioPlayer

    大家好,老司机学Xamarin系列又来啦!上一篇MvvmCross插件精选文末提到,Xamarin平台下,一直没找到一个可用的跨平台AudioPlayer插件.那就自力更生,让我们就自己来写一个吧! ...

  3. EF Codefirst 多对多关系 操作中间表的 增删改查(CRUD)

    前言 此文章只是为了给新手程序员,和经验不多的程序员,在学习ef和lambada表达式的过程中可能遇到的问题. 本次使用订单表和员工表建立多对多关系. 首先是订单表: public class Ord ...

  4. Oracle 中 union 和union all 的简单使用说明

    1.刚刚工作不久,经常接触oracle,但是对oracle很多东西都不是很熟.今天我们来了解一下union和union all的简单使用说明.Union(union all): 指令的目的是将两个 S ...

  5. Android-简单的图片验证码

    Android-图片验证码生成1.为啥要验证码?图片验证码在网络中使用的是比较普遍的.一般都是用来防止恶意破解密码.刷票.论坛灌水.刷页等.2.怎样的验证码比较好?验证码的获取方式无非就两种,一种是后 ...

  6. 美图WEB开放平台环境配置

    平台环境配置 1.1.设置crossdomain.xml 下载crossdomain.xml文件,把解压出来的crossdomain.xml文件放在您保存图片或图片来源的服务器根目录下,比如: htt ...

  7. LINQ系列:LINQ to SQL Concat/Union

    1. Concat 单列Concat var expr = (from p in context.Products select p.ProductName) .Concat( from c in c ...

  8. nodejs 使用fs实现多级联动

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAA0gAAAEdCAIAAAC5WdDhAAAgAElEQVR4nO3da3Mc153f8X4feq5lFR

  9. MVC4做网站后台:栏目管理1、添加栏目-续

    栏目类型跟原来一样分为常规栏目.单页栏目和外部链接.根据栏目类型的不同要隐藏相应的表单和验证(服务器端验证).另外一个是父栏目必须是常规栏目才行,easyui-combotree要用到树形json数据 ...

  10. 应用程序框架实战二十九:Util Demo介绍

    上文介绍了我选择EasyUi作为前端框架的原因,并发放了最新Demo.本文将对这个Demo进行一些介绍,以方便你能够顺利运行起来. 这个Demo运行起来以后,是EasyUi的一个简单CRUD操作,数据 ...