2013年6月10日 星期一

Jie的懶教學:Android Http通訊協定資料存取 (GET,POST)

Jie的懶教學,這次來教大家來寫一隻Android的懶人HttpClient程式:

在Android使用Http通訊協定(GET,POST)讀取網頁或做資料存取的時候,
每次都要做一堆try catch處理
POST的時後設定的NameValuePair形態使用也不太習慣,
基本上POST的形態都是字串,所以接口乾脆直接改成用HashMap<String,String>來設定感覺比較親切些。

當然最重要的原因還是懶,懶人就是要想盡辦法一行就搞定:D


懶人前:
package com.example.jiehttpclient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JieHttpClient {

    public static String GET(String url){
        String result = "";
        HttpGet get = new HttpGet(url);
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse httpResponse = httpClient.execute(get);
            if(httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                result = EntityUtils.toString(httpResponse.getEntity());
            }else{
                result = "JieHttpClient GET Fail";
            }
        }catch(ClientProtocolException e){
            System.out.println("JieHttpClient GET Error = "+e.getMessage().toString());
        }catch (IOException e){
            System.out.println("JieHttpClient GET Error = "+e.getMessage().toString());
        }catch (Exception e){
            System.out.println("JieHttpClient GET Error = "+e.getMessage().toString());
        }
        return result;
    }

    public static String POST(String url,HashMap<String,String> paramsMap){
        String result = "";
        HttpPost post = new HttpPost(url);

        try {

            if(paramsMap!=null){
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                for(Map.Entry<String,String> entry:paramsMap.entrySet()){
                    params.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
                }
                HttpEntity httpEntity = new UrlEncodedFormEntity(params,"utf-8");
                post.setEntity(httpEntity);
            }

            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse httpResponse = httpClient.execute(post);
            if(httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                result = EntityUtils.toString(httpResponse.getEntity());
            }else{
                result = "JieHttpClient POST Fail";
            }

        }catch(ClientProtocolException e){
            System.out.println("JieHttpClient POST Error = " + e.getMessage().toString());
        }catch (IOException e){
            System.out.println("JieHttpClient POST Error = " + e.getMessage().toString());
        }catch (Exception e){
            System.out.println("JieHttpClient POST Error = " + e.getMessage().toString());
        }
        return result;
    }
}


懶人後:
        //GET
        String result = JieHttpClient.GET("GET URL");

        //POST
        HashMap<String,String> params = new HashMap<String, String>();
        params.put("key1","value1");
        params.put("key2","value2");
        String result = JieHttpClient.POST("POST URL",params);

回傳的result字串可能是HTML,XML或JSON,就視狀況去處理啦~

完工,爆肝。

沒有留言:

張貼留言