[C#] 與Android共舞–手機post資料給Server

2012-11-22


最近在搞安卓,跟Server溝通是一定要的,這範例很簡單,就是我在Android 上面,透過POST 的方式傳資料給

Server ,則Server 收到值後直接回傳, Server side 是用asp.net C# 寫作..

現在直接來看Code

Server 端(C#):

建立一個echo.aspx 在aspx 得部分除了第一行全部都拿掉

只剩下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="echo.aspx.cs" Inherits="EchoService.echo" %>



再來就是C# 得部分:




using System;

namespace EchoService
{
public partial class echo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form.Count == 0)
{
Response.Write("{}");
}else
{
Response.Write(Request.Form[0]);
}
}
}
}




 


再來就是Android 的部分:


 


//傳送資料回Server 
//urlPath: 後端網址
//data: 資料
public static String SendHttpPost(String urlPath, String data) {

try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(urlPath);
httpPostRequest.setEntity(new StringEntity(data, HTTP.UTF_8));
httpPostRequest.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
httpPostRequest.setHeader("Accept-Encoding", "gzip");
HttpResponse response = (HttpResponse) httpclient
.execute(httpPostRequest);
HttpEntity entity = response.getEntity();
if (entity != null) {

InputStream instream = entity.getContent();
Header contentEncoding = response
.getFirstHeader("Content-Encoding");
if (contentEncoding != null
&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
String resultString = convertStreamToString(instream);
return resultString;
}

} catch (Exception e) {
Log.e("WebUtil", e.toString());
}
return "";
}


 

 

private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the BufferedReader
* return null which means there's no more data to read. Each line will
* appended to a StringBuilder and returned as String.
*
* (c) public domain:
* http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/
* 11/a-simple-restful-client-at-android/
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}





呼叫方式:



String res = SendHttpPost(
"http://swap.no2don.com/echo.aspx", "{name:'許當麻',first_name:'當麻',last_name:'許'}");


結果:



照片



注意事項:


 


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.