我该如何解决缺少必需的oauth参数:oauth_signature_method?

时间:2018-12-13 07:08:10

标签: android android-studio android-volley

我正在尝试从Api获取数据,但是发生了错误。  我有类似的参数:

 oauth_consumer_key-    String  --Your API key when you registered as a developer
        oauth_signature_method- String--    The method used to generate the signature (only HMAC-SHA1 is supported)
        oauth_timestamp -Int    --The date and time, expressed in the number of seconds since January 1, 1970 00:00:00 GMT. The timestamp value must be a positive integer and must be equal or greater than the timestamp used in previous requests
        oauth_nonce -String--   A randomly generated string for a request that can be combined with the timestamp to produce a unique value
        oauth_version   -String --MUST be "1.0"
        oauth_signature-    String--    The signature, a consistent reproducible concatenation of the request elements into a single string. The string is used as an input in hashing or signing algorithms.
        method  -String --MUST be "recipes.search"

我的班级看上去就像我在使用Volley库来获取数据的地方:

      final static private String APP_METHOD = "GET";
        final static private String APP_KEY = "app key is here";
        final static private String APP_SECRET = "secret key is here&";
        final static private String APP_URL = "http://platform.fatsecret.com/rest/server.api";
        private static final String HMAC_SHA1_ALGORITHM = "HMAC-SHA1";


        private static String paramify(String[] params) {
            String[] p = Arrays.copyOf(params, params.length);
            Arrays.sort(p);
            return join(p, "&");
        }

        private static String join(String[] array, String separator) {
            StringBuilder b = new StringBuilder();
            for (int i = 0; i < array.length; i++) {
                if (i > 0)
                    b.append(separator);
                b.append(array[i]);
            }
            return b.toString();
        }

    //generating nonce value
        private static String nonce() {
            Random r = new Random();
            StringBuilder n = new StringBuilder();
            for (int i = 0; i < r.nextInt(8) + 2; i++)
                n.append(r.nextInt(26) + 'a');
            return n.toString();
        }
    //timestamp
        Long tsLong = System.currentTimeMillis() / 1000;
        int ts = Integer.parseInt(tsLong.toString());

        private static String[] generateOauthParams(int page) {
            return new String[]{
                    "oauth_consumer_key=" + APP_KEY,
                    "oauth_signature_method=HMAC-SHA1",
                    "oauth_timestamp=" +
                            Long.valueOf(System.currentTimeMillis() * 2).toString(),
                    "oauth_nonce=" + nonce(),
                    "oauth_version=1.0",
                    "format=json"};
        }

        private static String signature(String[] params) {
            String[] p = {RecipeActivity.APP_METHOD, Uri.encode(RecipeActivity.APP_URL), Uri.encode(paramify(params))};
            String s = join(p, "&");
            SecretKey sk = new SecretKeySpec(APP_SECRET.getBytes(), HMAC_SHA1_ALGORITHM);
            try {
                Mac m = Mac.getInstance(HMAC_SHA1_ALGORITHM);
                m.init(sk);
              haang =  Uri.encode(new String(Base64.encode(m.doFinal(s.getBytes()), Base64.DEFAULT)).trim());
                return haang;
            } catch (java.security.NoSuchAlgorithmException | java.security.InvalidKeyException e) {
                Log.w("FatSecret_TEST FAIL", e.getMessage());
                return null;
            }
        }

      //signature method
//is is never used
        public JSONObject searchRecipes(String searchRecipes, int page) {
            List<String> params = new ArrayList<>(Arrays.asList(generateOauthParams(page)));
            String[] template = new String[1];
            params.add("method=recipes.search");
            params.add("search_expression=" + Uri.encode(searchRecipes));
            params.add("oauth_signature=" + signature(params.toArray(template)));

            JSONObject foods = null;
            try {
                URL url = new URL(APP_URL + "?" + paramify(params.toArray(template)));
                URLConnection api = url.openConnection();
                String line;
                StringBuilder builder = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(api.getInputStream()));
                while ((line = reader.readLine()) != null) builder.append(line);
                JSONObject food = new JSONObject(builder.toString());   // { first
                foods = food.getJSONObject("recipes");                    // { second
            } catch (Exception exception) {
                Log.e("Json error", exception.toString());
                exception.printStackTrace();
            }
            return foods;
        }


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_recipe);

           System.out.println("haang"+haang);
            final RequestQueue requestQueue = Volley.newRequestQueue(RecipeActivity.this);

          StringRequest stringRequest=new StringRequest(Request.Method.GET, APP_URL, new com.android.volley.Response.Listener<String>() {
              @Override
              public void onResponse(String response) {

                  Log.i("success", response);

              }
          }, new com.android.volley.Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                  Log.i("error",error.getMessage());

              }
          });
          requestQueue.add(stringRequest);



        }
    }

但是我遇到了错误。我正试图以Xml格式获取数据。这是我的日志。我是这个概念的新手,不知道我在做什么错。

  <error xmlns="http://platform.fatsecret.com/api/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://platform.fatsecret.com/api/1.0/ http://platform.fatsecret.com/api/1.0/fatsecret.xsd">
        <code>2</code>
        <message>Missing required oauth parameter: oauth_signature_method</message>
    </error>

为什么我遇到此错误。请指导我。

0 个答案:

没有答案