Android远程服务器身份验证使用HttpUrlConnection不发送登录/密码参数

时间:2012-02-28 18:00:39

标签: android httpurlconnection android-asynctask

我有这段代码:

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


        Log.d( "Inner myURL: " , myUrl );
        Log.d( "myEmail: " , myEmail );
        Log.d( "myPass: " , myPassword );

        Authenticator.setDefault(new Authenticator()
        {
            protected PasswordAuthentication getPasswordAuthentication() 
            {
                return new PasswordAuthentication( myEmail, myPassword.toCharArray());
            }
        });         

        String response = null;

        try 
        {
            final URL url = new URL(myUrl);
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setUseCaches(false);

            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));
            }

            response = builder.toString();      
            Log.d( "After call, response: " , " " + response);
        } 
        catch (Exception e) 
        {
                Log.d( "Exception: " , "Yup");
                e.printStackTrace();
        }

        return response;
    }       

}

但是当它执行时,登录/密码不会在post请求中发送到服务器。知道如何解决这个问题并发送这些参数吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

HttpClient client = new DefaultHttpClient();
        try {
            HttpPost httppost = new HttpPost(url);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

            nameValuePairs.add(new BasicNameValuePair("user", user));
            nameValuePairs.add(new BasicNameValuePair("password", password));


            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = client.execute(httppost);

            String responseBody = EntityUtils.toString(response.getEntity());

            System.out.println("Responce is :: " + responseBody);

        } catch (Exception e) {
            e.printStackTrace();
        }