如何在服务器端提取数据?

时间:2011-04-30 14:28:42

标签: android http http-post

我在客户端使用了以下代码(Android模拟器)。

HttpClient client=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://117.192.xxx.xxx:8080/System_Alpha/");
List pairs=new  ArrayList();
String strUsername=username.getText().toString();
String strPassword=password.getText().toString();
pairs.add(new BasicNameValuePair("username", strUsername));
pairs.add(new BasicNameValuePair("password", strPassword));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response= client.execute(httpPost);

我的问题是,在服务器端,我如何提取这些值?那就是用户名和密码?

1 个答案:

答案 0 :(得分:0)

这取决于你在服务器端的内容。

说:如果您有一个java servlet,只需在doGet(resp。doPost)方法中检索必要的数据:

final String userName = (String) request.getParameter("userName");
final String password = (String) request.getParameter("password");

更新1
下面是一个简单的servlet示例,它使用上面的两个参数对用户进行身份验证,然后发回一个xml响应:

public class LoginServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException
    {
        response.setContentType("text/xml");
        final ServletOutputStream out = response.getOutputStream();
        try
        {
            final String userName = (String) request.getParameter("userName");
            final String password = (String) request.getParameter("password");
            final boolean authenticated = login(userName, password);
            if (authenticated)
                out.println("<login><status>SUCCESS</status></login>");
            else
                out.println("<login><status>FAIL</status></login>");
        }
        catch (Exception e)
        {
            out.println("<login><status>ERROR</status></login>");
        }
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException
    {
        this.doGet(request, response);
    }

    private boolean login(final String userName, final String password)
    {
        // TODO: authenticate the user and return the result: true/false
    }
}

web.xml中,您通过写下来声明您的servlet:

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>[yourpackagename].LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet/*</url-pattern>
</servlet-mapping>

其中[yourpackagename]是声明LoginServlet的包。

这样,如果所有这些都在名为Try的Web应用程序中,并且您部署它,则可以通过http http://localhost:8080/Try/LoginServlet/访问您的登录servlet。

更新2
要从HttpResponse检索数据,您需要:

HttpEntity entity = response.getEntity();
final InputStream inputStream = entity.getContent();

您可以根据其中包含的数据来处理此InputStream

如果您需要响应实体的String值:

HttpEntity entity = response.getEntity();
final String responseText = EntityUtils.toString(entity);