如何将Magento REST Api与Android应用程序连接? [英] How to connect Magento REST Api with Android Application?

查看:67
本文介绍了如何将Magento REST Api与Android应用程序连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Magento的电子商务网站.如何使用Magento上的REST API连接到我的Android应用程序?

I have a e-commerce website which uses Magento. How can I use the REST API on Magento to connect to my Android Application?

推荐答案

用于调用静态Web服务的完整示例 RestFulWebservice.java此活动类

Complete sample for calling restful webservice RestFulWebservice.java this activity class

public class RestFulWebservice extends Activity {


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.rest_ful_webservice);  

        final Button GetServerData = (Button) findViewById(R.id.GetServerData);

        GetServerData.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                // WebServer url change it accordingly
                String serverURL = "http://androidexample.com/media/webservice/JsonReturn.php";

                // Use AsyncTask execute Method To Prevent ANR Problem
                new LongOperation().execute(serverURL);
            }
        });    

    }


    // Class with extends AsyncTask class

    private class LongOperation  extends AsyncTask<String, Void, Void> {

        // Required initialization

        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        private ProgressDialog Dialog = new ProgressDialog(RestFulWebservice.this);
        String data =""; 
        TextView uiUpdate = (TextView) findViewById(R.id.output);
        TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
        int sizeData = 0;  
        EditText serverText = (EditText) findViewById(R.id.serverText);


        protected void onPreExecute() {
            // NOTE: You can call UI Element here.

            //Start Progress Dialog (Message)

            Dialog.setMessage("Please wait..");
            Dialog.show();

            try{
                // Set Request parameter
                data +="&" + URLEncoder.encode("data", "UTF-8") + "="+serverText.getText();

            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 

        }

        // Call after onPreExecute method
        protected Void doInBackground(String... urls) {

            /************ Make Post Call To Web Server ***********/
            BufferedReader reader=null;

                 // Send data 
                try
                { 

                   // Defined URL  where to send data
                   URL url = new URL(urls[0]);

                  // Send POST data request

                  URLConnection conn = url.openConnection(); 
                  conn.setDoOutput(true); 
                  OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
                  wr.write( data ); 
                  wr.flush(); 

                  // Get the server response 

                  reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                  StringBuilder sb = new StringBuilder();
                  String line = null;

                    // Read Server Response
                    while((line = reader.readLine()) != null)
                        {
                               // Append server response in string
                               sb.append(line + "
");
                        }

                    // Append Server Response To Content String 
                   Content = sb.toString();
                }
                catch(Exception ex)
                {
                    Error = ex.getMessage();
                }
                finally
                {
                    try
                    {

                        reader.close();
                    }

                    catch(Exception ex) {}
                }

            /*****************************************************/
            return null;
        }

        protected void onPostExecute(Void unused) {
            // NOTE: You can call UI Element here.

            // Close progress dialog
            Dialog.dismiss();

            if (Error != null) {

                uiUpdate.setText("Output : "+Error);

            } else {

                // Show Response Json On Screen (activity)
                uiUpdate.setText( Content );

             /****************** Start Parse Response JSON Data *************/

                String OutputData = "";
                JSONObject jsonResponse;

                try {

                     /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
                     jsonResponse = new JSONObject(Content);

                     /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
                     /*******  Returns null otherwise.  *******/
                     JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");

                     /*********** Process each JSON Node ************/

                     int lengthJsonArr = jsonMainNode.length();  

                     for(int i=0; i < lengthJsonArr; i++) 
                     {
                         /****** Get Object for each JSON node.***********/
                         JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

                         /******* Fetch node values **********/
                         String name       = jsonChildNode.optString("name").toString();
                         String number     = jsonChildNode.optString("number").toString();
                         String date_added = jsonChildNode.optString("date_added").toString();


                         OutputData += " Name           : "+ name +" 
 "
                                     + "Number      : "+ number +" 
 "
                                     + "Time                : "+ date_added +" 
 " 
                                     +"--------------------------------------------------
";


                    }
                 /****************** End Parse Response JSON Data *************/    

                     //Show Parsed Output on screen (activity)
                     jsonParsed.setText( OutputData );


                 } catch (JSONException e) {

                     e.printStackTrace();
                 }


             }
        }

    }

}

rest_full_webservice.xml

rest_full_webservice.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  android:fillViewport="true"
  android:background="#FFFFFF"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <EditText
        android:paddingTop="20px"
        android:id="@+id/serverText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="" />
    <Button
        android:paddingTop="10px"
        android:id="@+id/GetServerData"
        android:text="Restful Webservice Call"
        android:cursorVisible="true"
        android:clickable="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_gravity="center_horizontal"
    /> 
    <TextView
        android:paddingTop="20px"
        android:textStyle="bold"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Server Response (JSON): " />
    <TextView
        android:paddingTop="16px"
        android:id="@+id/output"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Output : Click on button to get server data." />

    <TextView
        android:paddingTop="20px"
        android:textStyle="bold"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Parsed JSON : " />
    <TextView
        android:paddingTop="16px"
        android:id="@+id/jsonParsed"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
       />

</LinearLayout>
</ScrollView>

manifest.xml不会忘记添加互联网许可

manifest.xml don't forgot to add internet permission

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

我认为您需要OAUth 2.0, 您可以从 https://github.com/cbitstech/xsi-android 获取示例 抄写员库是执行此操作的最佳方法.

I think you required OAUth 2.0, you can get sample from https://github.com/cbitstech/xsi-android scribe library is the best way to do this.

这篇关于如何将Magento REST Api与Android应用程序连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆