(每次学习一点xamarin就做个学习笔记和视频来加深记忆巩固知识)
如有不正确的地方,请帮我指正。
简介
在安卓中通过Http请求网络数据可以使用安卓原生的HttpURLConnection类和Square公司的开源库OKHttp3。
使用HttpURLConnection进行Get请求
直接上C#代码吧(记得在AndroidManifest.xml文件中声明网络权限<uses-permissionandroid:name="android.permission.INTERNET"/>)
先定自定义个接口,里面定义两个回调方法
public interface IHttpListener
{
void OnFinish(string response);//请求完成后调用
void OnError(Exception e);//请求出错后调用
}
再添加个HttpHelper类,定义下面的静态方法
/// <summary>
/// 使用android原生的HttpURLConnection类来进行http请求
/// </summary>
/// <param name="address">请求地址</param>
/// <returns>请求得到的内容</returns>
public static void SendHttpRequest(string address, IHttpListener listener)
{
new Thread(new ThreadStart(
() =>
{
#region 子线程执行请求
HttpURLConnection conn = null;
try
{
URL url = new URL(address);
conn = (HttpURLConnection)url.OpenConnection(); //打开http连接
conn.RequestMethod = "GET"; //设置为get请求
conn.ConnectTimeout = 6000; //设置连接超时时间为6秒
conn.ReadTimeout = 6000; //设置读取数据超时时间为6秒
conn.DoInput = true; //允许接收数据,以后就可以使用conn.InputStream (Get请求时用)
//conn.DoOutput = true; //允许发送数据,以后就可以使用conn.OutputStream (Post请求时用)
StringBuilder sb = new StringBuilder();
Stream inStream = conn.InputStream;
using (StreamReader reader = new StreamReader(inStream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
}
if (listener != null)
listener.OnFinish(sb.ToString()); //回调OnFinish()方法
}
catch (Exception e)
{
if (listener != null)
listener.OnError(e); //回调OnError()方法
}
finally
{
if (conn != null)
conn.Disconnect(); //关闭连接
}
#endregion
}
)).Start();
}
使用Square.OKHttp3进行Get请求
需要从NuGet中下载此包。
/// <summary>
/// 使用Square公司开源库OKHttp3来进行http请求
/// 需要在NuGet中下载Square.OkHttp3包
/// </summary>
/// <param name="address">请求地址</param>
/// <param name="callback">实现了ICallback接口的对象</param>
public static void SendHttpRequestByOkHttp3(string address, Square.OkHttp3.ICallback callback)
{
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.Url(address)
.Get()
.Build();
httpClient.NewCall(request).Enqueue(callback);//在Enqueue()方法内部自动开好子线程了
}
在Activity中分别使用这两个方法
public class SecondActivity : AppCompatActivity, IHttpListener, Square.OkHttp3.ICallback
{
private TextView textView;
public void OnError(Exception e)//自定义接口中的回调方法
{
//必须调用RunOnUiThread()方法切换到主线程来更新UI
this.RunOnUiThread(() =>
{
Toast.MakeText(this, "请求出错" + e.Message, ToastLength.Long).Show();
});
}
public void OnFinish(string response)//自定义接口中的回调方法
{
//必须调用RunOnUiThread()方法切换到主线程来更新UI
this.RunOnUiThread(() =>
{
textView.Text = response;
Toast.MakeText(this, "请求成功", ToastLength.Short).Show();
});
}
public void OnFailure(ICall p0, IOException p1)//OkHttp3的回调方法
{
this.RunOnUiThread(() =>
{
Toast.MakeText(this, "请求出错" + p1.Message, ToastLength.Long).Show();
});
}
public void OnResponse(ICall p0, Response p1)//OkHttp3的回调方法
{
string s = p1.Body().String();//从响应流中读出数据保存到变量S中
this.RunOnUiThread(() =>
{
textView.Text = s;
Toast.MakeText(this, "请求成功", ToastLength.Short).Show();
});
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Second);
textView = this.FindViewById<TextView>(Resource.Id.textView1);
Button btnSend = this.FindViewById<Button>(Resource.Id.btnSend);
btnSend.Click += delegate { HttpHelper.SendHttpRequest("http://www.hao123.com", this); };
//btnSend.Click += delegate { HttpHelper.SendHttpRequestByOkHttp3("http://www.hao123.com", this); };
}
}
完整代码和视频在我上传的CSDN资源中 http://download.csdn.net/download/junshangshui/10049305