doujue1246 2017-07-15 04:44
浏览 215

如何使用Magento Rest API

I am new in Magento. I want to use Magento Rest API for Android. I got oAuth_token and oauth_verifier.After passing oAuth_token and oauth_verifier,I got an error.Invalid auth/bad request (got a 400, expected HTTP/1.1 20X or a redirect) <br/>oauth_problem=parameter_absent&oauth_parameters_absent=oauth_verifier.

Here is my code:

 <?php
    ini_set('display_errors', '1');
       $callbackUrl_1 = "http://demo.com/magento.com/admin123.php";
    $callbackUrl = "http://demo.com/magento.com/sendToken.php";
    $temporaryCredentialsRequestUrl = "http://demo.com/magento.com/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
    //$adminAuthorizationUrl = 'http://demo.com/magento.com/admin123/oAuth_authorize';
    $adminAuthorizationUrl = 'http://demo.com/magento.com/oauth/authorize';
    $accessTokenRequestUrl = 'http://demo.com/magento.com/oauth/token';
    $apiUrl = 'http://demo.com/magento.com/api/rest';
    $consumerKey = '88a6142021c1cdfed92b0954a94fc066';
    $consumerSecret = 'bedc0ede692fe06d4b12821bb21f7c3b';

    session_start();
    //echo "SESSION state".$_SESSION['state'];

    if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {

        $_SESSION['state'] = 0;
    }
    try {
        $authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
        $oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
        $oauthClient->enableDebug();


        if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {

            $requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
            $_SESSION['secret'] = $requestToken['oauth_token_secret'];
            $_SESSION['state'] = 1;

            //echo "oauth_token ".$requestToken['oauth_token']."<br>";
            //echo "oauth_token_secret ".$requestToken['oauth_token_secret'];die;

            header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']."&oauth_token_secret=".$requestToken['oauth_token_secret']);

            exit;
        } else if ($_SESSION['state'] == 1) {
        //  echo "oauth_token ".$_GET['oauth_token'];die;   
            $oauthClient->setToken($_GET['oauth_token'],$_SESSION['oauth_verifier']);
            $accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);

            $_SESSION['state'] = 2;
            $_SESSION['token'] = $accessToken['oauth_token'];
            $_SESSION['secret'] = $accessToken['oauth_token_secret'];

            $_SESSION['example'] = $accessToken['oauth_token'];

            header('Location: ' . $callbackUrl);
            exit;
        } else {
            $_SESSION['state'] = 0;
            $oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);

            $resourceUrl = "$apiUrl/products";
            $oauthClient->fetch($resourceUrl,array(), 'GET', array('Content-Type' => 'application/json', 'Accept' => 'application/json'));
            $productsList = json_decode($oauthClient->getLastResponse());
            print_r($productsList);
        }
    } catch (OAuthException $e) {
        print_r($e->getMessage());
        echo "&lt;br/&gt;";
        print_r($e->lastResponse);
    }


    ?>
  • 写回答

1条回答 默认 最新

  • drphfy1198 2017-07-17 12:43
    关注

    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

    <?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 don't forgot to add internet permission

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

    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.

    For Information visit below URLs:-

    https://stackoverflow.com/a/35083651

    https://stackoverflow.com/a/32934934

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog