.Net程序員安卓學習之路4:使用xutils Get Post數據


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

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

該服務說明如下:

image

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

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

第一步:實現界面

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

image

布局代碼如:

 

       <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串

image

我們要做的就是將返回的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(); 
        } 

        });
    }

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

image

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(); 
        } 

        }); 
    }

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

image

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM