Android:没有通过基本身份验证

时间:2016-03-15 13:46:23

标签: java android authorization httprequest

我的目标是从API获取xml。我使用的API uri,包括参数http://webservices.ns.nl/ns-api-treinplanner?fromStation=Roosendaal&toStation=Eindhoven。我获得了用户名和密码,我认为可能是基本授权。

我尝试了各种各样的东西,例如使用Authenticator,格式为http://username:password@webservices.ns.nl/ns-api-treinplanner,但在很多SO搜索结束时,我最终得到了带有基本授权setRequestProperty的内容。

我将代码放入一个似乎正常工作的AsyncTask中,所以我将把doInBackground内的代码放在这里。

由于我首先得到的java FileNotFoundException没有给我太多信息,我发现如何使用getErrorStream来了解更多信息。

            InputStream in;
            int resCode;

            try {
                URL url = new URL("http://webservices.ns.nl/ns-api-treinplanner?fromStation=Roosendaal&toStation=Eindhoven");

                String userCredentials = "username:password";
                String encoding = new String(android.util.Base64.encode(userCredentials.getBytes(), Base64.DEFAULT));

                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestProperty("Authorization", "Basic " + encoding);
                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);

                try {
                    resCode = urlConnection.getResponseCode();
                    if (resCode == HttpURLConnection.HTTP_OK) {
                        Log.i("rescode","ok");
                        in = urlConnection.getInputStream();
                    } else {
                        Log.i("rescode","not ok");
                        in = urlConnection.getErrorStream();
                    }
                    BufferedReader bufferedReader = new BufferedReader(
                            new InputStreamReader(in));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuilder.append(line).append("\n");
                    }
                    bufferedReader.close();
                    return stringBuilder.toString();
                }
                finally{
                    urlConnection.disconnect();
                }
            }
            catch(Exception e) {
                Log.e("ERROR", e.getMessage(), e);
                return null;
            }

然后,在onPostExecute中打印响应,但我得到的响应是

 <?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
<soap:Header></soap:Header>
<soap:Body><soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>006:No customer found for the specified username and password</faultstring></soap:Fault>
</soap:Body></soap:Envelope>

这当然不对,在这种情况下应该给出完整的xml火车航行建议。

我测试了我的浏览器,并使用名为Postman的HTTP请求工具返回了正确的xml,因此所有的uri,参数,用户名和密码都是正确的。

1 个答案:

答案 0 :(得分:1)

使用的编码是错误的。使用的base64编码随机返回中间的空格,添加encoding = encoding.replaceAll("\\s+","");实际修复它。

相关问题