之所以做這個demo,是爲了測試c#中的網絡請求是否能在安卓中正確使用
最終效果圖如下
網絡請求是在網絡上找的代碼,修復了無參post報錯問題,封裝成一個類庫
代碼如下:
public class HttpHelper
{
public static HttpWebResponse CreateGetHttpResponse(string url, int timeout, string userAgent, CookieCollection cookies)
{
HttpWebRequest request = null;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
//對服務端證書進行有效性校驗(非第三方權威機構頒發的證書,如自己生成的,不進行驗證,這裏返回true)
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10; //http版本,默認是1.1,這裏設置爲1.0
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "GET";
//設置代理UserAgent和超時
//request.UserAgent = userAgent;
//request.Timeout = timeout;
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
return request.GetResponse() as HttpWebResponse;
}
/// <summary>
/// 創建POST方式的HTTP請求
/// </summary>
public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies)
{
HttpWebRequest request = null;
//如果是發送HTTPS請求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
//ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
//request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//設置代理UserAgent和超時
//request.UserAgent = userAgent;
//request.Timeout = timeout;
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
if ((parameters == null || parameters.Count == 0))
{
request.ContentLength = 0;
}
//發送POST數據
if (!(parameters == null || parameters.Count == 0))
{
StringBuilder buffer = new StringBuilder();
int i = 0;
foreach (string key in parameters.Keys)
{
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, parameters[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, parameters[key]);
i++;
}
}
byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
string[] values = request.Headers.GetValues("Content-Type");
return request.GetResponse() as HttpWebResponse;
}
/// <summary>
/// 獲取請求的數據
/// </summary>
public static string GetResponseString(HttpWebResponse webresponse)
{
using (Stream s = webresponse.GetResponseStream())
{
StreamReader reader = new StreamReader(s, Encoding.UTF8);
return reader.ReadToEnd();
}
}
/// <summary>
/// 驗證證書
/// </summary>
private static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
if (errors == SslPolicyErrors.None)
return true;
return false;
}
}
天氣預報採用了中國天氣網接口 如http://www.weather.com.cn/data/cityinfo/101270101.html
省份和城市採用兩個spanner,點擊查詢請求網絡獲取結果,結果顯示在下方的textview中
下面是佈局代碼
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:gravity="center"
android:layout_height="80dp">
<TextView
android:text="選擇省份:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textColor="#f0f0f0" />
<Spinner
android:id="@+id/spn_sf"
android:layout_width="190dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:gravity="center"
android:layout_height="80dp">
<TextView
android:text="選擇城市:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textColor="#f0f0f0" />
<Spinner
android:id="@+id/spn_cs"
android:layout_width="190dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<Button
android:id="@+id/MyButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="查詢" />
<TextView
android:text="狀態"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView1" />
</LinearLayout>
下面是頁面代碼:
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Threading;
using Android.Util;
using System.Net;
using System.Collections.Generic;
namespace TestAndroidWeather
{
[Activity(Label = "TestAndroidWeather", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity , Android.Widget.Spinner.IOnItemSelectedListener
{
int count = 1;
public string str_code= "101010100";
Spinner spn_sf, spn_cs;
String[] citys, ctcode;
ArrayAdapter adapt, adapt2;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.MyButton);
TextView textView1 = FindViewById<TextView>(Resource.Id.textView1);
spn_sf = FindViewById<Spinner>(Resource.Id.spn_sf);
spn_cs = FindViewById<Spinner>(Resource.Id.spn_cs);
adapt = new ArrayAdapter<String>(this, Android.Resource.Layout.SimpleSpinnerItem, new String[] { "北京", "上海", "天津", "重慶", "香港", "澳門", "黑龍江", "吉林", "遼寧", "內蒙古", "河北", "河南", "山東", "山西", "江蘇", "安徽", "陝西", "寧夏", "甘肅", "青海", "湖北", "湖南", "浙江", "江西", "福建", "貴州", "四川", "廣東", "廣西", "雲南", "海南", "新疆", "西藏", "臺灣" });
adapt.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
spn_sf.Adapter = adapt;
// spn_sf.
spn_sf.OnItemSelectedListener = this;
button.Click += delegate {
new Thread(
() => {
try
{
Dictionary<string, string> seatDic = new Dictionary<string, string>{
};
str_code= ctcode[spn_cs.SelectedItemPosition];
RunOnUiThread(() => { textView1.Text = "正在連接服務器"; });
string str = HttpHelper.HttpHelper.GetResponseString(HttpHelper.HttpHelper.CreatePostHttpResponse("http://www.weather.com.cn/data/cityinfo/" + str_code + ".html", seatDic, 5000, "", new CookieCollection()));
Org.Json.JSONObject json = new Org.Json.JSONObject(str);
Org.Json.JSONObject weatherinfo = json.GetJSONObject("weatherinfo");
RunOnUiThread(()=> { textView1.Text = String.Format("城市::{0}\n天氣狀況{1}\n溫度{2}-{3}", weatherinfo.GetString("city"), weatherinfo.GetString("weather") ,weatherinfo.GetString("temp1"), weatherinfo.GetString("temp2")) ; });
Log.Error("tag", "str==>>{0}" , str);
}
catch (Exception e)
{
RunOnUiThread(() => { textView1.Text = String.Format("錯誤{0}", e.Message); });
Log.Error("err", "err==>>{0}" , e.Message);
}
}).Start();
};
}
public void setitems(String cf)
{
try
{
String[] maincitys = new String[] { "北京", "上海", "天津", "重慶", "香港", "澳門", "黑龍江", "吉林", "遼寧", "內蒙古", "河北", "河南", "山東", "山西", "江蘇", "安徽", "陝西", "寧夏", "甘肅", "青海", "湖北", "湖南", "浙江", "江西", "福建", "貴州", "四川", "廣東", "廣西", "雲南", "海南", "新疆", "西藏", "臺灣" };
for (int i = 0; i < maincitys.Length; i++)
{
if (maincitys[i].Equals(cf.ToString()))
{
switch (i + 1)
{
case 1: citys = new String[] { "北京" }; ctcode = new String[] { "101010100" }; break;
case 2: citys = new String[] { "上海" }; ctcode = new String[] { "101020100" }; break;
case 3: citys = new String[] { "天津" }; ctcode = new String[] { "101030100" }; break;
case 4: citys = new String[] { "重慶" }; ctcode = new String[] { "101040100" }; break;
case 5: citys = new String[] { "香港" }; ctcode = new String[] { "101320101" }; break;
case 6: citys = new String[] { "澳門" }; ctcode = new String[] { "101330101" }; break;
case 7:
citys = new String[] { "哈爾濱", "齊齊哈爾", "牡丹江", "大慶", "伊春", "雙鴨山", "鶴崗", "雞西", "佳木斯", "七臺河", "黑河", "綏化", "大興安嶺" };
ctcode = new String[] { "101050101", "101050201", "101050301", "101050901", "101050801", "101051301", "101051201", "101051101", "101050401", "101051002", "101050601", "101050501", "101050701" };
break;
case 8:
citys = new String[] { "長春", "延吉", "吉林", "白山", "白城", "四平", "松原", "遼源", "大安", "通化" };
ctcode = new String[] { "101060101", "101060301", "101060201", "101060901", "101060601", "101060401", "101060801", "101060701", "101060603", "101060501" };
break;
case 9:
citys = new String[] { "瀋陽", "大連", "葫蘆島", "盤錦", "本溪", "撫順", "鐵嶺", "遼陽", "營口", "阜新", "朝陽", "錦州", "丹東", "鞍山" };
ctcode = new String[] { "101070101", "101070201", "101071401", "101071301", "101070501", "101070401", "101071101", "101071001", "101070801", "101070901", "101071201", "101070701", "101070601", "101070301" };
break;
case 10:
citys = new String[] { "呼和浩特", "呼倫貝爾", "錫林浩特", "包頭", "赤峯", "海拉爾", "烏海", "鄂爾多斯", "通遼" };
ctcode = new String[] { "101080101", "101081000", "101080901", "101080201", "101080601", "101081001", "101080301", "101080701", "101080501" };
break;
case 11:
citys = new String[] { "石家莊", "唐山", "張家口", "廊坊", "邢臺", "邯鄲", "滄州", "衡水", "承德", "保定", "秦皇島" };
ctcode = new String[] { "101090101", "101090501", "101090301", "101090601", "101090901", "101091001", "101090701", "101090801", "101090402", "101090201", "101091101" };
break;
case 12:
citys = new String[] { "鄭州", "開封", "洛陽", "平頂山", "焦作", "鶴壁", "新鄉", "安陽", "濮陽", "許昌", "漯河", "三門峽", "南陽", "商丘", "信陽", "周口", "駐馬店" };
ctcode = new String[] { "101180101", "101180801", "101180901", "101180501", "101181101", "101181201", "101180301", "101180201", "101181301", "101180401", "101181501", "101181701", "101180701", "101181001", "101180601", "101181401", "101181601" };
break;
case 13:
citys = new String[] { "濟南", "青島", "淄博", "威海", "曲阜", "臨沂", "煙臺", "棗莊", "聊城", "濟寧", "菏澤", "泰安", "日照", "東營", "德州", "濱州", "萊蕪", "濰坊" };
ctcode = new String[] { "101120101", "101120201", "101120301", "101121301", "101120710", "101120901", "101120501", "101121401", "101121701", "101120701", "101121001", "101120801", "101121501", "101121201", "101120401", "101121101", "101121601", "101120601" };
break;
case 14:
citys = new String[] { "太原", "陽泉", "晉城", "晉中", "臨汾", "運城", "長治", "朔州", "忻州", "大同", "呂梁" };
ctcode = new String[] { "101100101", "101100301", "101100601", "101100401", "101100701", "101100801", "101100501", "101100901", "101101001", "101100201", "101101101" };
break;
case 15:
citys = new String[] { "南京", "蘇州", "崑山", "南通", "太倉", "吳縣", "徐州", "宜興", "鎮江", "淮安", "常熟", "鹽城", "泰州", "無錫", "連雲港", "揚州", "常州", "宿遷" };
ctcode = new String[] { "101190101", "101190401", "101190404", "101190501", "101190408", "101190406", "101190801", "101190203", "101190301", "101190901", "101190402", "101190701", "101191201", "101190201", "101191001", "101190601", "101191101", "101191301" };
break;
case 16:
citys = new String[] { "合肥", "巢湖", "蚌埠", "安慶", "六安", "滁州", "馬鞍山", "阜陽", "宣城", "銅陵", "淮北", "蕪湖", "毫州", "宿州", "淮南", "池州" };
ctcode = new String[] { "101220101", "101221601", "101220201", "101220601", "101221501", "101221101", "101220501", "101220801", "101221401", "101221301", "101221201", "101220301", "101220901", "101220701", "101220401", "101221701" };
break;
case 17:
citys = new String[] { "西安", "韓城", "安康", "漢中", "寶雞", "咸陽", "榆林", "渭南", "商洛", "銅川", "延安" };
ctcode = new String[] { "101110101", "101110510", "101110701", "101110801", "101110901", "101110200", "101110401", "101110501", "101110601", "101111001", "101110300" };
break;
case 18:
citys = new String[] { "銀川", "固原", "中衛", "石嘴山", "吳忠" };
ctcode = new String[] { "101170101", "101170401", "101170501", "101170201", "101170301" };
break;
case 19:
citys = new String[] { "蘭州", "白銀", "慶陽", "酒泉", "天水", "武威", "張掖", "甘南", "臨夏", "平涼", "定西", "金昌" };
ctcode = new String[] { "101160101", "101161301", "101160401", "101160801", "101160901", "101160501", "101160701", "101050204", "101161101", "101160301", "101160201", "101160601" };
break;
case 20:
citys = new String[] { "西寧", "海北", "海西", "黃南", "果洛", "玉樹", "海東", "海南" };
ctcode = new String[] { "101150101", "101150801", "101150701", "101150301", "101150501", "101150601", "101150201", "101150401" };
break;
case 21:
citys = new String[] { "武漢", "宜昌", "黃岡", "恩施", "荊州", "神農架", "十堰", "咸寧", "襄陽", "孝感", "隨州", "黃石", "荊門", "鄂州" };
ctcode = new String[] { "101200101", "101200901", "101200501", "101201001", "101200801", "101201201", "101201101", "101200701", "101200201", "101200401", "101201301", "101200601", "101201401", "101200301" };
break;
case 22:
citys = new String[] { "長沙", "邵陽", "常德", "郴州", "吉首", "株洲", "婁底", "湘潭", "益陽", "永州", "岳陽", "衡陽", "懷化", "韶山", "張家界" };
ctcode = new String[] { "101250101", "101250901", "101250601", "101250501", "101251501", "101250301", "101250801", "101250201", "101250701", "101251401", "101251001", "101250401", "101251201", "101250202", "101251101" };
break;
case 23:
citys = new String[] { "杭州", "湖州", "金華", "寧波", "麗水", "紹興", "衢州", "嘉興", "台州", "舟山", "溫州" };
ctcode = new String[] { "101210101", "101210201", "101210901", "101210401", "101210801", "101210501", "101211001", "101210301", "101210601", "101211101", "101210701" };
break;
case 24:
citys = new String[] { "南昌", "萍鄉", "九江", "上饒", "撫州", "吉安", "鷹潭", "宜春", "新餘", "景德鎮", "贛州" };
ctcode = new String[] { "101240101", "101240901", "101240201", "101240301", "101240401", "101240601", "101241101", "101240501", "101241001", "101240801", "101240701" };
break;
case 25:
citys = new String[] { "福州", "廈門", "龍巖", "南平", "寧德", "莆田", "泉州", "三明", "漳州" };
ctcode = new String[] { "101230101", "101230201", "101230701", "101230901", "101230301", "101230401", "101230501", "101230801", "101230601" };
break;
case 26:
citys = new String[] { "貴陽", "安順", "赤水", "遵義", "銅仁", "六盤水", "畢節", "凱里", "都勻" };
ctcode = new String[] { "101260101", "101260301", "101260208", "101260201", "101260601", "101260801", "101260701", "101260501", "101260401" };
break;
case 27:
citys = new String[] { "成都", "瀘州", "內江", "涼山", "阿壩", "巴中", "廣元", "樂山", "綿陽", "德陽", "攀枝花", "雅安", "宜賓", "自貢", "甘孜州", "達州", "資陽", "廣安", "遂寧", "眉山", "南充" };
ctcode = new String[] { "101270101", "101271001", "101271201", "101271601", "101271901", "101270901", "101272101", "101271401", "101270401", "101272001", "101270201", "101271701", "101271101", "101270301", "101271801", "101270601", "101271301", "101270801", "101270701", "101271501", "101270501" };
break;
case 28:
citys = new String[] { "廣州", "深圳", "潮州", "韶關", "湛江", "惠州", "清遠", "東莞", "江門", "茂名", "肇慶", "汕尾", "河源", "揭陽", "梅州", "中山", "德慶", "陽江", "雲浮", "珠海", "汕頭", "佛山" };
ctcode = new String[] { "101280101", "101280601", "101281501", "101280201", "101281001", "101280301", "101281301", "101281601", "101281101", "101282001", "101280901", "101282101", "101281201", "101281901", "101280401", "101281701", "101280905", "101281801", "101281401", "101280701", "101280501", "101280800" };
break;
case 29:
citys = new String[] { "南寧", "桂林", "陽朔", "柳州", "梧州", "玉林", "桂平", "賀州", "欽州", "貴港", "防城港", "百色", "北海", "河池", "來賓", "崇左" };
ctcode = new String[] { "101300101", "101300501", "101300510", "101300301", "101300601", "101300901", "101300802", "101300701", "101301101", "101300801", "101301401", "101301001", "101301301", "101301201", "101300401", "101300201" };
break;
case 30:
citys = new String[] { "昆明", "保山", "楚雄", "德宏", "紅河", "臨滄", "怒江", "曲靖", "思茅", "文山", "玉溪", "昭通", "麗江", "大理" };
ctcode = new String[] { "101290101", "101290501", "101290801", "101291501", "101290301", "101291101", "101291201", "101290401", "101290901", "101290601", "101290701", "101291001", "101291401", "101290201" };
break;
case 31:
citys = new String[] { "海口", "三亞", "儋州", "瓊山", "通什", "文昌" };
ctcode = new String[] { "101310101", "101310201", "101310205", "101310102", "101310222", "101310212" };
break;
case 32:
citys = new String[] { "烏魯木齊", "阿勒泰", "阿克蘇", "昌吉", "哈密", "和田", "喀什", "克拉瑪依", "石河子", "塔城", "庫爾勒", "吐魯番", "伊寧" };
ctcode = new String[] { "101130101", "101131401", "101130801", "101130401", "101131201", "101131301", "101130901", "101130201", "101130301", "101131101", "101130601", "101130501", "101131001" };
break;
case 33:
citys = new String[] { "拉薩", "阿里", "昌都", "那曲", "日喀則", "山南", "林芝" };
ctcode = new String[] { "101140101", "101140701", "101140501", "101140601", "101140201", "101140301", "101140401" };
break;
case 34:
citys = new String[] { "臺北", "高雄" };
ctcode = new String[] { "101340102", "101340201" };
break;
default:
break;
}
}
adapt2 = new ArrayAdapter<String>(this, Android.Resource.Layout.SimpleSpinnerItem, citys);
// adapt2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, citys);
adapt2.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
spn_cs.Adapter = adapt2;
// spn_cs.setAdapter(adapt2);
}
}
catch (Exception ex)
{
}
}
public void OnItemSelected(AdapterView parent, View view, int position, long id)
{
String selectsf = spn_sf.SelectedItem.ToString();
//Toast.makeText(setcity.this, selectsf, Toast.LENGTH_LONG).show();
setitems(selectsf);
}
public void OnNothingSelected(AdapterView parent)
{
//throw new NotImplementedException();
}
}
}
主要邏輯是,通過spanner選中城市,獲取城市代碼,然後通過接口獲取數據,提取結果展示
項目源碼
http://pan.baidu.com/s/1pL290XP