401 从 android 连接到 PrestaShop Web 服务时出错

问题描述 投票:0回答:2

我尝试在 PrestaShop 中调用 Web 服务,但收到 401 未授权错误。即使我已经通过了用户名密钥。我也尝试了身份验证器,但收到错误 HttpRetryingError。

在下面找到我所做的代码片段。

方法一:

final String username = "key_here";
final String password = "";// leave it empty

URL urlToRequest = new URL(urlStr);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type",
"text/xml;charset=utf-8");

String authToBytes = username + ":" + password;
//....
byte[] authBytes = org.apache.commons.codec.binary.Base64.encodeBase64(authToBytes.getBytes());
String authBytesString = new String(authBytes);
//then your code
urlConnection.setRequestProperty("Authorization","Basic " + authBytesString);

int statusCode = urlConnection.getResponseCode(); ---> i get 401
if (statusCode != HttpURLConnection.HTTP_OK) {
// throw some exception
InputStream in =
new BufferedInputStream(urlConnection.getInputStream());
Log.e("tag", getResponseText(in));
}

方法二

final String username = "keyvaluehere";
final String password = "";// leave it empty
String authToBytes = username + ":" + password;
byte[] authBytes = org.apache.commons.codec.binary.Base64.encodeBase64(authToBytes.getBytes());
String authBytesString = new String(authBytes);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 30000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 30000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);

HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization","Basic " +authBytesString);
try {
HttpResponse response = httpclient.execute(httpGet);
String strResponse = EntityUtils.toString(response.getEntity());
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return strResponse;
}
return strResponse;
}catch(ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

我什至尝试将字符串作为 ws_key 和键值传递,我什至将 url 称为 http://[email protected]/api/namehere

但它也不起作用。 请帮忙。

android web-services prestashop
2个回答
8
投票

我知道这是一个老问题,但我想我可以提供帮助。

检查.htaccess 文件。它应该有这样的行:

RewriteRule . - [E=REWRITEBASE:/]
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteRule ^api$ api/ [L]

RewriteRule ^api/(.*)$ %{ENV:REWRITEBASE}webservice/dispatcher.php?url=$1 [QSA,L]

第二行告诉Apache如何处理授权。


0
投票

我出现错误 401,需要进行更正配置,激活 Web 服务并创建 Clave。安装 Linux 服务并使用 RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] 是我的解决方案

© www.soinside.com 2019 - 2024. All rights reserved.