如何在android中解析magento json webservice

时间:2014-03-12 08:49:35

标签: android json magento

我是android的新手,无法解析Magento webservices中的数据。 我正在使用kso​​ap2库从webservices获取数据。 以下是我用来获取数据的代码。

在异步任务中,我调用webservice并在对象中获取响应

package com.example.soaptest;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalHashtable;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

private static final String NAMESPACE =     "urn:Magento";//<targetNamespace="urn:Magento">
    private static final String URL = "http://yourdomain.com/magento/index.php/api/v2_soap";//Remove ?wsdl=1 from main URL
    private static final String SOAP_ACTION ="urn:Mage_Api_Model_Server_V2_HandlerAction";//<soap:operation soapAction="urn:Mage_Api_Model_Server_V2_HandlerAction"/>
    private  static final String Method_Name="login";//<operation name="login">

    SoapSerializationEnvelope env;
    HttpTransportSE androidHttpTransport;

    String sessionId = "";
    String customerList = "";
   String attrList = "";
    Object result;

    TextView tvsessId,tvcustList;
    EditText etuserName,etapiKey;
    Button btnsubmit,btnCancel;
    Context mContext;

    String userName = null;
    String apiKey = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         etuserName = (EditText)findViewById(R.id.editTextUName1);
         etapiKey = (EditText)findViewById(R.id.editTextApiKey2);

         tvsessId = (TextView)findViewById(R.id.textViewSessionId1);
         tvcustList = (TextView)findViewById(R.id.textViewCustList5);

         btnsubmit = (Button)findViewById(R.id.btnSubmit1);
         btnCancel = (Button)findViewById(R.id.btnCancel2);

         btnsubmit.setOnClickListener(this);
         btnCancel.setOnClickListener(this);

         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
         .permitAll().build();
         StrictMode.setThreadPolicy(policy);


    }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btnSubmit1:
            try {

                if (Utils.isNetworkAvailable(MainActivity.this)) {
                    new MyTask().execute();

                } else {
                    Toast.makeText(getApplicationContext(), "No Network Connection!!!", Toast.LENGTH_SHORT).show();
                }



            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }           
            break;

        case R.id.btnCancel2:
            etuserName.setText("");
            etapiKey.setText("");
            break;
        }
    }

    class MyTask extends AsyncTask<String, Void, Void> {

        ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading...");
            pDialog.show();

        }

        @Override
        protected Void doInBackground(String... params) {

            userName = "test";
            apiKey = "test123";
            getSoapData(userName,apiKey);               
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (null != pDialog && pDialog.isShowing()) {
                pDialog.dismiss();
            }

                tvsessId.setText(sessionId);
                tvcustList.setText(customerList);             

        }
    }
    private void getSoapData(String userName,String apiKey) {
        // TODO Auto-generated method stub
        try {
            env = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            env.dotNet = false;
            env.xsd = SoapSerializationEnvelope.XSD;
            env.enc = SoapSerializationEnvelope.ENC;
                    SoapObject request = new SoapObject(NAMESPACE, Method_Name); 
            request.addProperty("username", userName);
            request.addProperty("apiKey", apiKey);

            System.out.println("Request is :"+request);

            env.setOutputSoapObject(request); 
            androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.debug = true;
            (new MarshalHashtable()).register(env);  
            androidHttpTransport.call(SOAP_ACTION, env);
            result = env.getResponse();             
            sessionId = result.toString();
                    request = new SoapObject(NAMESPACE,"customerCustomerList");
                    name="customerCustomerList">
            request.addProperty("sessionId",sessionId);

            env.setOutputSoapObject(request);
            androidHttpTransport.call(SOAP_ACTION, env);
            result = env.getResponse(); 

            customerList = result.toString();

            Log.d("Customer List", customerList);

            tvcustList.setText(customerList);

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

}

1 个答案:

答案 0 :(得分:0)

这是完整的解决方案。如您所见,我正在扩展Thread,并在initRequest()方法上运行所有内容。

package com.example.magentomobileapp;

import java.io.IOException;
import java.net.URL;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class SoapMagento extends Thread {

    private static final String NAMESPACE = "urn:Magento";
    private static final String URL = "http://yourshop.com/api/v2_soap/";

    public void initRequest() {
        this.start();
    }

    @Override
    public void run() {
        try {
            try {
                SoapSerializationEnvelope env = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                env.dotNet = false;
                env.xsd = SoapSerializationEnvelope.XSD;
                env.enc = SoapSerializationEnvelope.ENC;
                SoapObject request = new SoapObject(NAMESPACE, "login");
                request.addProperty("username", "yourusernam");
                request.addProperty("apiKey", "apikeypass");
                env.setOutputSoapObject(request);
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.call("", env);
                Object result = env.getResponse();
                System.out.println("SESSION TEST" +  result.toString());
                Log.d("THIS IS A NEW SESSION ID: ", result.toString());

                // customers list
                String sessionId = result.toString();
                request = new SoapObject(NAMESPACE, "customerCustomerList");
                request.addProperty("sessionId",sessionId );
                env.setOutputSoapObject(request);
                androidHttpTransport.call("", env);
                result = env.getResponse();
                Log.d("Customer List", result.toString());
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("THERE WAS AN ERROR");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}