Я пытаюсь реализовать подключение к API WooCommerce с помощью API, чтобы получить список продуктов, после прочтения документации woocommerce о реализации более http
я кодирую эти строки
но я получаю Unauthorized
ошибку, есть удивительный совет, когда я не использую Retroft
и использую HttpURLConnection
вместо этого, я не получаю никакой ошибки, и эта реализация работает нормально
Реализация с Retrofit
public class ClientSettings {
/* localhost */
public static final String BASE_URL = "http://192.168.1.104/wordpress/";
public static final String WOOCOMMERCE_CONSUMER_KEY = "ck_515737c30d289b81dad0babc99b7327753b97054";
public static final String WOOCOMMERCE_CONSUMER_SECRET = "cs_b80449eda376e68228c2c465b57bfd0aca873fdd";
}
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();
}
}
Retrofit
:
@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();
}
OAuthInterceptor
класс имплантации
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();
}
с использованием HttpURLConnection
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";
}