2015年3月25日 星期三

Android-用 HttpURLConnection 取代 Parse SDK 查詢功能

更改日期 :
20150706 避免傳送中文造成的Exception

前幾天實作直接利用 HttpClient 取得資料回饋
但發現雖然都可以正常執行
但發現到這個要準備去棄用了
以下是官方的圖示















以下是連線到 Parse 並且取得資料
以下 ID 、 KEY 是連接Parse必給的參數
若沒需求可把附加的方法去除
以下是利用HttpURLConnection連線

public class TodoTask extends AsyncTask<Void,Void,String>{
    
    private String _api;
    private String _strJson;

    public TodoTask(String api, String strJson){
        this._api = api;
        this._strJson = strJson;
    }

    @Override
    public void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    public String doInBackground(Void... arg0) {
        URL url;
        HttpURLConnection connection = null;  
        try {
            //Create connection
            url = new URL(_api);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");

            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Content-Length", "" + 
                Integer.toString(_strJson.getBytes().length));
            connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            connection.addRequestProperty("Application-Id","your project id");
            connection.addRequestProperty("API-Key","your project key");

            connection.setUseCaches (false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            connection.setConnectTimeout(5000);

            //Send request
            DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
            wr.write(_strJson.getBytes("utf-8"));
            wr.flush ();
            wr.close ();

            //Get Response    
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer(); 
            
            while((line = rd.readLine()) != null) {
                response.append(line);
                //response.append('\r');
            }
            rd.close();
            return response.toString();

        } catch (Exception e) {

            e.printStackTrace();
            return null;

        } finally {

            if(connection != null) {
                connection.disconnect(); 
            }
        }
    }

    @Override
    public void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.d("tagg","onPostExecute : "+result);
        if(result != null && !"".equals(result)){
            
        }
    }
}


參考來源 : 來源

歡迎轉載,請註明出處。

沒有留言:

張貼留言