到目前为止我有这个代码:

private class DownloadWebPageTask extends AsyncTask<String, Void, String>
{
        @Override
        protected String doInBackground(String... theParams)
        {
            String myUrl = theParams[0];
            String myEmail = theParams[1];
            String myPassword = theParams[2];

            HttpPost post = new HttpPost(myUrl);
            post.addHeader("Authorization","Basic "+ Base64.encodeToString((myEmail+":"+myPassword).getBytes(), 0 ));
            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            String response = null;

            try
            {
                    response = client.execute(post, responseHandler);
                InputStream content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                            new InputStreamReader(content));
                    String s = "";
                    while ((s = buffer.readLine()) != null)
                    {
                        response += s;
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

            return response;
        }


        @Override
        protected void onPostExecute(String result)
        {
            }

}

这段代码无法编译,因为我在以下方面遇到了困惑:
                response = client.execute(post, responseHandler);
                InputStream content = execute.getEntity().getContent();

我通过修改各种示例获得了该代码,但不确定客户端应该是什么对象,以及第一行是否只会让我获得服务器响应,或者我必须走获取 InputStream 并读取服务器的路线回应?

请帮助我了解如何正确执行此操作。

谢谢!

最佳答案

您可能想切换到 HttpURLConnection 。根据 this article 的说法,它的 API 比 HttpClient 的更简单,并且在 Android 上得到更好的支持。如果您确实选择使用 HttpURLConnection ,则身份验证非常简单:

Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("username", "password".toCharArray());
    }
});

之后,继续像往常一样使用 HttpURLConnection。一个简单的例子:
final URL url = new URL("http://example.com/");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
final InputStream is = conn.getInputStream();
final byte[] buffer = new byte[8196];
int readCount;
final StringBuilder builder = new StringBuilder();
while ((readCount = is.read(buffer)) > -1) {
    builder.append(new String(buffer, 0, readCount));
}
final String response = builder.toString();

10-08 12:33
查看更多