从 wordPress 网站获得 JSON 响应,使用基本身份验证的 woocommerce
Get JSON response from wordPress website, woocommerce with basic authentication
我正在开发一个 android 应用程序来获取 wordPress 网站的产品。
Woocommerce 插件安装在网站上。
我可以使用基本身份验证通过 Postman 软件获取该站点的 Json。 username 和 password 是 wordpress 网站生成的 api key 和 api secret。
当我将 GET methed 与 Postman 一起使用时没有问题。但是当我想通过 android 应用程序连接到网站时遇到问题,并出现错误。
这是我请求 Json 数据的方式:
public void newMyResponse(String url){
//RequestQueue requestQueue;
queue.add(new JsonArrayRequest(Request.Method.GET,
url,null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d("Products",response.toString());
for(int i=0; i<response.length(); i++){
try {
JSONObject jsonObject_products = response.getJSONObject(i);
Log.d("Items id: ",jsonObject_products.getString("id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error8", error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = "ck_...:cs_...";
String auth = "Basic "
+Base64.encodeToString(credentials.getBytes(),Base64.NO_WRAP);
headers.put("Content-Type", "application/json");
headers.put("Authorization", auth);
return headers;
}
});
好的,经过几天的搜索,我终于找到了问题所在。
我的网站使用带有自签名证书的 https。所以应用程序需要证书才能使用它。
首先,按照此处所述下载您的站点证书:
Export Certificate
所以我发现,最好的方法是将以下代码添加到要进行身份验证的 activity 的 oncreate 方法中:
hurlStack = new HurlStack() {
@Override
protected HttpURLConnection createConnection(java.net.URL url)
throws IOException {
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super
.createConnection(url);
try {
httpsURLConnection.setSSLSocketFactory(getSSLSocketFactory(getApplicationContext()));
} catch (Exception e) {
e.printStackTrace();
}
return httpsURLConnection;
}
};
queue = newRequestQueue(this, hurlStack);
我应该提到队列和 hurlStack 应该定义为:
private RequestQueue queue;
private HurlStack hurlStack;
然后,将您网站的证书添加到原始文件夹,在我的例子中,文件名为 certificate.and 将这些方法添加到您正在处理的 activity 中:
public SSLSocketFactory getSSLSocketFactory(Context context)
throws CertificateException, KeyStoreException, IOException,
NoSuchAlgorithmException, KeyManagementException {
// the certificate file will be stored in \app\src\main\res\raw folder path
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = context.getResources().openRawResource(R.raw.certificate);
Certificate ca = cf.generateCertificate(caInput);
caInput.close();
KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(tmf.getTrustManagers());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, wrappedTrustManagers, null);
return sslContext.getSocketFactory();
}
private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers) {
final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];
return new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return originalTrustManager.getAcceptedIssuers();
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
try {
if (certs != null && certs.length > 0) {
certs[0].checkValidity();
} else {
originalTrustManager
.checkClientTrusted(certs, authType);
}
} catch (CertificateException e) {
Log.w("checkClientTrusted", e.toString());
}
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
try {
if (certs != null && certs.length > 0) {
certs[0].checkValidity();
} else {
originalTrustManager
.checkServerTrusted(certs, authType);
}
} catch (CertificateException e) {
Log.w("checkServerTrusted", e.toString());
}
}
}};
}
我正在开发一个 android 应用程序来获取 wordPress 网站的产品。 Woocommerce 插件安装在网站上。 我可以使用基本身份验证通过 Postman 软件获取该站点的 Json。 username 和 password 是 wordpress 网站生成的 api key 和 api secret。 当我将 GET methed 与 Postman 一起使用时没有问题。但是当我想通过 android 应用程序连接到网站时遇到问题,并出现错误。 这是我请求 Json 数据的方式:
public void newMyResponse(String url){
//RequestQueue requestQueue;
queue.add(new JsonArrayRequest(Request.Method.GET,
url,null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d("Products",response.toString());
for(int i=0; i<response.length(); i++){
try {
JSONObject jsonObject_products = response.getJSONObject(i);
Log.d("Items id: ",jsonObject_products.getString("id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error8", error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = "ck_...:cs_...";
String auth = "Basic "
+Base64.encodeToString(credentials.getBytes(),Base64.NO_WRAP);
headers.put("Content-Type", "application/json");
headers.put("Authorization", auth);
return headers;
}
});
好的,经过几天的搜索,我终于找到了问题所在。 我的网站使用带有自签名证书的 https。所以应用程序需要证书才能使用它。 首先,按照此处所述下载您的站点证书: Export Certificate 所以我发现,最好的方法是将以下代码添加到要进行身份验证的 activity 的 oncreate 方法中:
hurlStack = new HurlStack() {
@Override
protected HttpURLConnection createConnection(java.net.URL url)
throws IOException {
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super
.createConnection(url);
try {
httpsURLConnection.setSSLSocketFactory(getSSLSocketFactory(getApplicationContext()));
} catch (Exception e) {
e.printStackTrace();
}
return httpsURLConnection;
}
};
queue = newRequestQueue(this, hurlStack);
我应该提到队列和 hurlStack 应该定义为:
private RequestQueue queue;
private HurlStack hurlStack;
然后,将您网站的证书添加到原始文件夹,在我的例子中,文件名为 certificate.and 将这些方法添加到您正在处理的 activity 中:
public SSLSocketFactory getSSLSocketFactory(Context context)
throws CertificateException, KeyStoreException, IOException,
NoSuchAlgorithmException, KeyManagementException {
// the certificate file will be stored in \app\src\main\res\raw folder path
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = context.getResources().openRawResource(R.raw.certificate);
Certificate ca = cf.generateCertificate(caInput);
caInput.close();
KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(tmf.getTrustManagers());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, wrappedTrustManagers, null);
return sslContext.getSocketFactory();
}
private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers) {
final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];
return new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return originalTrustManager.getAcceptedIssuers();
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
try {
if (certs != null && certs.length > 0) {
certs[0].checkValidity();
} else {
originalTrustManager
.checkClientTrusted(certs, authType);
}
} catch (CertificateException e) {
Log.w("checkClientTrusted", e.toString());
}
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
try {
if (certs != null && certs.length > 0) {
certs[0].checkValidity();
} else {
originalTrustManager
.checkServerTrusted(certs, authType);
}
} catch (CertificateException e) {
Log.w("checkServerTrusted", e.toString());
}
}
}};
}