[C#] 與Android共舞–透過GET方式傳資料給Server(含解決中文編碼問題)

2012-11-22


上一篇文章分享了透過POST 方式傳資料回Server,這一篇來談談有關於透過GET的方式傳遞
首先,如我預期的一樣,透過網址傳遞,會產生編碼問題,這邊我就順代解掉,希望有碰到的人
可以不用為此煩惱..
解說一下範例,手機傳遞給Server後,Server收到參數,直接印出來,然後手機再將資料取回,非常的簡單流程
中間只有傳遞不處理任何資料..
Server side (C#) :

using System;

namespace EchoService
{
    public partial class echoget : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString.Count > 0)
            {
                Response.Write(Server.UrlDecode(Request.QueryString.ToString()));
            }else
            {
                //如果沒有資料,就傳似Json空物件
                Response.Write("{}");
            }
        }
    }
}




Android 傳遞方式:

//透過Get 方法 取得資料
//其中包含將中文字的部分自動進行 URL Encode
//確保字符的正確
public static String GetStringByURL(String urlPath) {
    InputStream is = null;
    String result = "";
    try {
        HttpClient httpclient = new DefaultHttpClient();
        //下兩行就是為了處理,編碼問題,如果有中文部分這邊一次解決掉
        URL url = new URL(urlPath);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(),
                url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        HttpGet httpGet = new HttpGet(uri.toString());
        httpGet.setHeader("Content-type",
                "application/x-www-form-urlencoded; charset=utf-8");
        HttpResponse response = httpclient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        result = "";
        Log.e("WebUtil", "取資料時發生問題:" + e.toString());
    }
    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        result = "";
        Log.e("WebUtil", "Error converting result " + e.toString());
    }

    return result;
}


呼叫方式:

String result = WebUtil.GetStringByURL(http://swap.no2don.com/echoget.aspx?id=許當麻&age=29);


結果:

照片 (1)
希望,有幫到你..

注意事項:
1.其中傳輸我都是透過格式為UTF-8
2.網路的Permission 記得打開  需要在 AndroidManifest.xml 中加入
<uses-permission android:name="android.permission.INTERNET"/>


3.還有一個地方需再Activity 中加入:
// AllowPolicy
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);





當麻許的超技八 2014 | Donma Hsu Design.