.Net程式員安卓學習之路4:使用xutils Get Post資料

來源:互聯網
上載者:User

標籤:

前面使用了一些網路上找來的類進行網路訪問,後來發現了安卓開發中有一個國人寫的類庫xutils比較全面,也比較經典,故後續使用xutils類庫進行記錄。

本例服務端使用WCF來實現,寫好的WCF服務端在:http://www.cnblogs.com/madyina/p/3454741.html 下載部署即可

該服務說明如下:

這4個公開方法均返回一個User對象,其中最後一個還接收一個User對象。

下面我們就分別請求這4個資源。

第一步:實現介面

使用相對布局,放置2個按鈕,分別為【Get Test】和【Post Test】。

布局代碼如:

 

       <Button         android:id="@+id/btn_get"        android:layout_width="wrap_content"        android:layout_height="wrap_content"         android:text="Get Test"        android:onClick="btn_getTest"        />            <Button         android:layout_width="wrap_content"        android:layout_height="wrap_content"         android:layout_toRightOf="@+id/btn_get"        android:text="Post Test"        android:onClick="btn_postTest"        />

 

第二步:引入第三方Jar包:

分別在下面地址下載xutils包和FastJson包:

https://github.com/wyouflf/xUtils/blob/master/xUtils-2.6.14.jar
http://repo1.maven.org/maven2/com/alibaba/fastjson/

複製到eclipse中。

不過這個FastJson包真心有點太大了,希望能夠精簡一些。

然後加入網路存取權限:

<uses-permission android:name="android.permission.INTERNET"/>

在bin\AndroidManifest.xml中

第三步:實現網路GET方式訪問

服務中第一個方法如:

        [OperationContract]        [WebInvoke(UriTemplate = "GetPerson", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "GET")]        public User GetUser()        {            return new User { Age = "12", ID = "001", Name = "zhangsan" };        }

所以使用

http://192.168.1.6/UserService.svc/GetPerson 來進行訪問,如果訪問成功,服務會返回一個Json串

我們要做的就是將返回的Json串還原序列化成對象,再訪問對象的屬性。

Xutils為我們封裝並最佳化了Android網路訪問,所以現在寫存取碼較為輕鬆:

    public void btn_getTest(View v)    {        HttpUtils http = new HttpUtils();        String url = "http://192.168.1.6/UserService.svc/GetPerson";         RequestParams params = new RequestParams();         http.send(HttpMethod.GET, url, params, new RequestCallBack<String>() {         @Override         public void onSuccess(ResponseInfo<String> responseInfo) {         User userInfo=JSON.parseObject(responseInfo.result,User.class);         Toast.makeText(getApplicationContext(), "請求結果:" + userInfo.getName(), Toast.LENGTH_SHORT).show();         }         @Override         public void onFailure(HttpException error, String msg) {         Toast.makeText(getApplicationContext(), "訪問失敗" + msg, Toast.LENGTH_SHORT).show();         }         });    }

發送到虛擬機器運行效果如:

Get方式若要加參數只需加在Url中即可,所以第二個方法不再舉例。

第四步:實現網路POST方式訪問

POST方式無參情況較少,我們直接來看有BODY的情況。實現思路是將本機物件序列化成JSON串,POST給服務,將返回的資料再次還原序列化,如上例show出對象的屬性。

服務方法如:

        [OperationContract]        [WebInvoke(UriTemplate = "GetPersonPostById", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")]        public User GetUserPostById(User u)        {            return new User { Age = "15", ID = "005", Name = "laoliu" };        }

本次不同的是由於傳送的BODY格式是JSON格式,所以需要在POST請求中加入Content-Type,詳細代碼如下:

    public void btn_postTest(View v)    {        HttpUtils http = new HttpUtils();        String url = "http://192.168.1.6/UserService.svc/GetPersonPostById";         RequestParams params = new RequestParams();         /* //添加請求參數         params.addBodyParameter(key, value);*/         params.addHeader("Content-Type", "application/json");        User user=new User();        user.setName("mady");        user.setAge("1");        user.setID("123");        String jsonStr=JSON.toJSONString(user);         try {        params.setBodyEntity(new StringEntity(jsonStr));        } catch (UnsupportedEncodingException e) {        }        http.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {         @Override         public void onSuccess(ResponseInfo<String> responseInfo) {             User userInfo=JSON.parseObject(responseInfo.result,User.class);             Toast.makeText(getApplicationContext(), "請求結果:" + userInfo.getName(), Toast.LENGTH_SHORT).show();         }         @Override         public void onFailure(HttpException error, String msg) {         Toast.makeText(getApplicationContext(), "訪問失敗" + error.fillInStackTrace(), Toast.LENGTH_SHORT).show();         }         });     }

發送到虛擬機器運行效果如:

如此我們就完成了使用xutils簡化網路訪問。

.Net程式員安卓學習之路4:使用xutils Get Post資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.