如何将请求参数附加到当前的Android HttpUrlConnection调用

时间:2012-02-28 20:16:27

标签: android

我能够从Android程序向远程服务器发送请求,但似乎请求没有参数。如何附加参数?

这是我目前的代码:

    @Override
    protected String doInBackground(String... theParams) 
    {

        String myUrl = theParams[0];
        final String myEmail = theParams[1];
        final String myPassword = theParams[2];

        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.setRequestProperty("login", myEmail);
            conn.setRequestProperty("password", myPassword);

            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) 
        {

        }

        return response;
    }

所以现在我不确定如何使Authenticator密码/登录附加到请求并发送到服务器。知道我怎么能做到这一点吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

你只是这样做

final URL url = new URL(myUrl+"?login="+myEmail+"&password="+myPassword);

您不需要setRequestProperty行。这些实际上是设置你的Http Request的属性而不是查询参数。