У меня есть сайт Wordpress, и я хочу подключить его к приложению для Android с помощью API, но этот API не является общедоступным, поэтому я создал пользователя на веб-сайте и получил ключ потребителя и его секрет.теперь я хочу использовать эту информацию для вызова Retrofit конечным точкам API.
Я нашел некоторую документацию и следовал ей, чтобы реализовать это, но я все еще получаю нулевой ответ от Retrofit.
1.Вот как я строю модифицированное соединение
public class RetrofitConnection {
private static RetrofitConnection mInstance;
private static final String BASE_URL = "https://www.example.net/wp-json/wp/v2/";
private Retrofit mRetrofit;
private RetrofitConnection() {
String consumerKey = "***"; //api key
String consumerSecret = "***"; //api secret
OAuthInterceptor oauth1Woocommerce = new OAuthInterceptor.Builder()
.consumerKey(consumerKey)
.consumerSecret(consumerSecret)
.build();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.addInterceptor(oauth1Woocommerce)// Interceptor oauth1Woocommerce added
.build();
mRetrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
public static RetrofitConnection getInstance() {
if (mInstance == null) {
mInstance = new RetrofitConnection();
}
return mInstance;
}
public JobiumApi getJSONApi() {
return mRetrofit.create(JobiumApi.class);
}
}
2.Онтерцептор OAuth, который я основал в документации
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();
Log.d("URL", original.url().toString());
Log.d("URL", original.url().scheme());
Log.d("encodedpath", original.url().encodedPath());
Log.d("query", ""+original.url().query());
Log.d("path", ""+original.url().host());
Log.d("encodedQuery", ""+original.url().encodedQuery());
;
Log.d("method", ""+original.method());
////////////////////////////////////////////////////////////
final String nonce = new TimestampServiceImpl().getNonce();
final String timestamp = new TimestampServiceImpl().getTimestampInSeconds();
Log.d("nonce", nonce);
Log.d("time", timestamp);
String dynamicStructureUrl = original.url().scheme() + "://" + original.url().host() + original.url().encodedPath();
Log.d("ENCODED PATH", ""+dynamicStructureUrl);
String firstBaseString = original.method() + "&" + urlEncoded(dynamicStructureUrl);
Log.d("firstBaseString", firstBaseString);
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();
Log.d("Sorted","00--"+result.sort().asOauthBaseString());
String secoundBaseString = "&" + generatedBaseString;
if (firstBaseString.contains("%3F")) {
Log.d("iff","yess iff");
secoundBaseString = "%26" + urlEncoded(generatedBaseString);
}
String baseString = firstBaseString + secoundBaseString;
String signature = new HMACSha1SignatureService().getSignature(baseString, consumerSecret, "");
Log.d("Signature", signature);
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 customization: add request headers
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;
private int type;
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");
Log.d("TEST", encodedurl);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encodedurl;
}
}