Android 安卓通过改造实现与woocommerce api的连接并获得未经授权的错误

Android 安卓通过改造实现与woocommerce api的连接并获得未经授权的错误,android,wordpress,woocommerce,Android,Wordpress,Woocommerce,在阅读了WooCommerce关于通过http实现的文档后,我试图通过api实现与WooCommerce api的连接,以获取产品列表 但是我得到了未经授权的错误,有一个奇怪的提示,当我不使用Retroft并且使用HttpURLConnection时,我没有得到任何错误,这个实现工作正常 通过改装实施 OkHttp: @Provides @ApplicationScope public OkHttpClient okHttpClient(HttpLoggingInterceptor loggin

在阅读了WooCommerce关于通过
http实现的文档后,我试图通过api实现与WooCommerce api的连接,以获取产品列表

但是我得到了
未经授权的
错误,有一个奇怪的提示,当我不使用
Retroft
并且使用
HttpURLConnection
时,我没有得到任何错误,这个实现工作正常

通过
改装实施
OkHttp

@Provides
@ApplicationScope
public OkHttpClient okHttpClient(HttpLoggingInterceptor loggingInterceptor, Cache cache) {
    OAuthInterceptor oauth1Woocommerce = new OAuthInterceptor.Builder()
            .consumerKey(ClientSettings.WOOCOMMERCE_CONSUMER_KEY)
            .consumerSecret(ClientSettings.WOOCOMMERCE_CONSUMER_SECRET)
            .build();

    BasicOAuth basicOAuthWoocommerce = new BasicOAuth.Builder()
            .consumerKey(ClientSettings.WOOCOMMERCE_CONSUMER_KEY)
            .consumerSecret(ClientSettings.WOOCOMMERCE_CONSUMER_SECRET)
            .build();

    return new OkHttpClient.Builder()
            .connectTimeout(90, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .addInterceptor(loggingInterceptor)
            .addInterceptor(BASE_URL.startsWith("http://")?  oauth1Woocommerce : basicOAuthWoocommerce)
            .cache(cache)
            .build();
}
}

改装

@Provides
@ApplicationScope
public Retrofit retrofit(OkHttpClient okHttpClient, Gson gson, RxJavaCallAdapterFactory rxJavaCallAdapterFactory) {
    return new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(rxJavaCallAdapterFactory)
            .client(okHttpClient)
            .baseUrl(mBaseUrl)
            .build();
}
OAuthiInterceptor
类实现

public class OAuthInterceptor implements Interceptor {
    private static final String OAUTH_CONSUMER_KEY = "oauth_consumer_key";
    private static final String OAUTH_NONCE = "oauth_nonce";
    private static final String OAUTH_SIGNATURE = "oauth_signature";
    private static final String OAUTH_SIGNATURE_METHOD = "oauth_signature_method";
    private static final String OAUTH_SIGNATURE_METHOD_VALUE = "HMAC-SHA1";
    private static final String OAUTH_TIMESTAMP = "oauth_timestamp";
    private static final String OAUTH_VERSION = "oauth_version";
    private static final String OAUTH_VERSION_VALUE = "1.0";

    private final String consumerKey;
    private final String consumerSecret;

    private OAuthInterceptor(String consumerKey, String consumerSecret) {
        this.consumerKey = consumerKey;
        this.consumerSecret = consumerSecret;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        HttpUrl originalHttpUrl = original.url();

        final String nonce = new TimestampServiceImpl().getNonce();
        final String timestamp = new TimestampServiceImpl().getTimestampInSeconds();

        String dynamicStructureUrl = original.url().scheme() + "://" + original.url().host() + original.url().encodedPath();

        String firstBaseString = original.method() + "&" + urlEncoded(dynamicStructureUrl);
        String generatedBaseString = "";

        if (original.url().encodedQuery() != null) {
            generatedBaseString = original.url().encodedQuery() + "&oauth_consumer_key=" + consumerKey + "&oauth_nonce=" + nonce + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + timestamp + "&oauth_version=1.0";
        } else {
            generatedBaseString = "oauth_consumer_key=" + consumerKey + "&oauth_nonce=" + nonce + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + timestamp + "&oauth_version=1.0";

        }

        ParameterList result = new ParameterList();
        result.addQuerystring(generatedBaseString);
        generatedBaseString = result.sort().asOauthBaseString();

        String secoundBaseString = "&" + generatedBaseString;

        if (firstBaseString.contains("%3F")) {
            secoundBaseString = "%26" + urlEncoded(generatedBaseString);
        }

        String baseString = firstBaseString + secoundBaseString;

        String signature = new HMACSha1SignatureService().getSignature(baseString, consumerSecret, "");

        HttpUrl url = originalHttpUrl.newBuilder()
                .addQueryParameter(OAUTH_SIGNATURE_METHOD, OAUTH_SIGNATURE_METHOD_VALUE)
                .addQueryParameter(OAUTH_CONSUMER_KEY, consumerKey)
                .addQueryParameter(OAUTH_VERSION, OAUTH_VERSION_VALUE)
                .addQueryParameter(OAUTH_TIMESTAMP, timestamp)
                .addQueryParameter(OAUTH_NONCE, nonce)
                .addQueryParameter(OAUTH_SIGNATURE, signature)
                .build();

        Request.Builder requestBuilder = original.newBuilder()
                .url(url);

        Request request = requestBuilder.build();
        return chain.proceed(request);
    }

    public static final class Builder {

        private String consumerKey;
        private String consumerSecret;

        public Builder consumerKey(String consumerKey) {
            if (consumerKey == null) throw new NullPointerException("consumerKey = null");
            this.consumerKey = consumerKey;
            return this;
        }

        public Builder consumerSecret(String consumerSecret) {
            if (consumerSecret == null) throw new NullPointerException("consumerSecret = null");
            this.consumerSecret = consumerSecret;
            return this;
        }

        public OAuthInterceptor build() {
            if (consumerKey == null) throw new IllegalStateException("consumerKey not set");
            if (consumerSecret == null) throw new IllegalStateException("consumerSecret not set");

            return new OAuthInterceptor(consumerKey, consumerSecret);
        }
    }

    public String urlEncoded(String url) {
        String encodedurl = "";
        try {
            encodedurl = URLEncoder.encode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodedurl;
    }
}
APIService
接口

public interface APIServices {
    @GET("wp-json/wc/v2/products")
    Call<List<ProductDetails>> getAllProducts();
}

您是否找到了改造问题的解决方案,我也面临着同样的问题。@Abdullah不幸的是,没有,我无法检查此链接,我是新的,即使在改造后也无法找到使其适用于我的方法this@Abdullah谢谢。我打开了颤振,现在不使用java:)
public interface APIServices {
    @GET("wp-json/wc/v2/products")
    Call<List<ProductDetails>> getAllProducts();
}
    final String BASE_SITE = "mysite.com/wp";
    final String BASE_URL = "http://"+BASE_SITE+"/wp-json/wc/v2/products";
    final String COSTUMER_KEY="ck_515737c30d289b81dad0babc99b7327753b97054";
    String COSTUMER_SECRET ="cs_b80449eda376e68228c2c465b57bfd0aca873fdd";

    String METHORD="GET";//change API method eg POST,PUT, DELETE etc (ONLY FOR THIS EXAMPLE FOR LIB LIKE RETROFIT,OKHTTP, The Are Dynamic Way)

    final String nonce=new TimestampServiceImpl().getNonce();
    final String timestamp=new TimestampServiceImpl().getTimestampInSeconds();

    String firstEncodedString =METHORD+"&"+encodeUrl(BASE_URL);

    String parameterString="oauth_consumer_key="+COSTUMER_KEY+"&oauth_nonce="+nonce+"&oauth_signature_method=HMAC-SHA1&oauth_timestamp="+timestamp+"&oauth_version=1.0";
    String secoundEncodedString="&"+encodeUrl(parameterString);

    String baseString=firstEncodedString+secoundEncodedString;

    String signature=new HMACSha1SignatureService().getSignature(baseString,COSTUMER_SECRET,"");

    //Signature is encoded before parsing (ONLY FOR THIS EXAMPLE NOT NECESSARY FOR LIB LIKE RETROFIT,OKHTTP)
    signature=encodeUrl(signature);

    Log.d("SignatureAfter ENCODING",signature);


    final String finalSignature = signature;//BECAUSE I PUT IN SIMPLE THREAD NOT NECESSARY
    final String parseUrl=BASE_URL+"?"+"oauth_signature_method=HMAC-SHA1&oauth_consumer_key="+COSTUMER_KEY+"&oauth_version=1.0&oauth_timestamp="+timestamp+"&oauth_nonce="+nonce+"&oauth_signature="+ finalSignature;

    new Thread() {
        @Override
        public void run() {

            String data = getJSON(parseUrl);
            if (onGettingProducts != null) {
                onGettingProducts.onProducts(data);
            }
        }
    }.start();
    emptyRecord.setVisibility(View.GONE);
}

/*getJSON*/

public String getJSON(String url) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        Log.d("urlioz", "" + c.getURL());
        c.connect();
        int status = c.getResponseCode();
        Log.d("staus", "" + status);
        switch (status) {
            case 200:
            case 401:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                Log.e("RESonse here ", sb.toString());
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
    } catch (IOException ex) {
    } finally {
        if (c != null) {
            try {
                c.disconnect();
            } catch (Exception ex) {
            }
        }
    }
    return "failed";
}