使用基本身份验证的POST在Android上失败但在C#中有效

我有一个正在开发的应用程序,需要我将数据发布到第三方API.我从一开始就一直在努力进行身份验证,并且不断进一步推迟,现在我陷入困境.

我曾尝试使用Authenticator,但已阅读所有有关某些Android版本中出现错误的信息:Authentication Example

我尝试了几种不同的选项,包括Apache Commons HTTP Library,但没有成功.毕竟,我决定确保API不是痛点.所以我写了一个快速的WinForms程序来测试API,它在第一次尝试时完美运行.因此,我正在使用的想法和我使用的API看起来都很好,但我迫切需要一些指导,以解释为什么Java代码不起作用.

示例如下:

C#代码每次都有效:

        System.Net.ServicePointManager.Expect100Continue = false;
        // Create a request using a URL that can receive a post. 
        WebRequest request = WebRequest.Create(addWorkoutUrl);
        // Set the Method property of the request to POST.
        request.Method = "POST";
        // Create POST data and convert it to a byte array.
        string postData = "distance=4000&hours=0&minutes=20&seconds=0&tenths=0&month=08&day=01&year=2011&typeOfWorkout=standard&weightClass=H&age=28";
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        request.Headers["X-API-KEY"] = apiKey;
        request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
        request.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.
        WebResponse response = request.GetResponse();
        // display the status.
        MessageBox.Show(((HttpWebResponse)response).StatusDescription);
        // Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
        // display the content.
        MessageBox.Show(responseFromServer);
        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();

Android的Java代码,当前返回500:内部服务器错误,但我相信这是我的错.

    URL url;
    String data = "distance=4000&hours=0&minutes=20&seconds=0&tenths=0&month=08&day=01&year=2011&typeOfWorkout=standard&weightClass=H&age=28";
HttpURLConnection connection = null;
    //Create connection
    url = new URL(urlBasePath);
    connection = (HttpURLConnection)url.openConnection();
    connection.setConnectTimeout(10000);
    connection.setUseCaches(false);
connection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
    connection.setRequestProperty("Accept","*/*");
    connection.setRequestProperty("X-API-KEY", apiKey);
    connection.setRequestProperty("Authorization", "Basic " +
    Base64.encode((username + ":" + password).getBytes("UTF-8"), Base64.DEFAULT));
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes("UTF-8").length));

    DataOutputStream wr = new DataOutputStream(connection.getoutputStream());
    wr.write(data.getBytes("UTF-8"));
    wr.flush();
    wr.close();
    statusCode = connection.getResponseCode();
    statusReason = connection.getResponseMessage();
    //At this point, I have the 500 error...

解决方法:

我发现了问题,最终解决了上面评论中提到的根本原因之后的解决方案.

我在我的示例中使用了Base64.encode(),但我需要使用Base64.encodetoString().

不同之处在于encode()返回byte []和encodetoString()返回我期望的字符串.

希望这会帮助被此抓住的其他人.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...