2015年3月25日 星期三

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

Use HttpClient can  repaly Parse SDK inquire function
如果只要連到Parse取得資料還要裝SDK?
SDK程序太複雜( 基本上是不會的 )?
現在只要用簡單的方法就可以取得資料

public class Task extends AsyncTask<Void,Void,String>{
        private String url;
        private String applicationID;
        private String clientKey;
        private List<NameValuePair> list;
        
        public Task(String url, String applicationID, 
                String clientKey, List<NameValuePair> list) {
            this.url = url;
            this.applicationID = applicationID;
            this.clientKey = clientKey;
            this.list = list;
        }

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

        @Override
        public String doInBackground(Void... arg0) {
            String result = null;
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost post = new HttpPost(url);

                post.setHeader("X-Parse-Application-Id", applicationID);
                post.setHeader("X-Parse-REST-API-Key", clientKey);

                post.setEntity(new UrlEncodedFormEntity(list));

                HttpResponse response = httpClient.execute(post);

                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                String line;
                StringBuffer responseBuffer = new StringBuffer();
                while ((line = rd.readLine()) != null) {
                    responseBuffer.append(line);
                }
                rd.close();
                result = responseBuffer.toString();
                
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        public void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }

調用方法
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("name", "JJ"));
        parameters.add(new BasicNameValuePair("Address", "US"));        
        
        Connection connectioni = new Connection();
        new Task("https://api.parse.com/functions/query85481", 
                "Application-ID", 
                "API-Key", 
                parameters).execute();

 歡迎轉載,請註明出處。

沒有留言:

張貼留言