服务器 - 从请求中读取参数(post)

时间:2011-08-13 23:16:05

标签: android

我的客户端中有以下代码:

    Log.v(TAG, "Trying to Login");
    HttpClient client = new DefaultHttpClient();
    EditText etxt_user = (EditText) findViewById(R.id.username);
    EditText etxt_pass = (EditText) findViewById(R.id.password);
    String username1 = etxt_user.getText().toString();
    String password1 = etxt_pass.getText().toString();
    HttpPost httppost = new HttpPost("http://10.0.2.2:8888");
    Log.v(TAG, "message1");         
    //add your Data
    List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
    nvps.add(new BasicNameValuePair("username", username1));
    nvps.add(new BasicNameValuePair("password", password1));

    try {
          UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
          httppost.setEntity(p_entity);
          //Execute HTTP Post Request
          HttpResponse response = client.execute(httppost);

          Log.v(TAG,"message2");
          Log.v(TAG, response.getStatusLine().toString());
          HttpEntity responseEntity = response.getEntity();

我的网络服务有以下代码:

public Source invoke(Source request){
        String replyElement = new String("hello world");
        StreamSource reply = new StreamSource(new StringReader(replyElement));
        String replyElement2 = new String("hello world 2");
        StreamSource reply2 =  new StreamSource(new StringReader(replyElement2));
        String amount = null;
        if (ws_ctx == null)throw new RuntimeException("DI failed on ws_ctx.");
        if (request == null) {
            System.out.println("Getting input from query string");
            // Grab the message context and extract the request verb.
            MessageContext msg_ctx = ws_ctx.getMessageContext();
            String x = msg_ctx.toString();
            System.out.println("The value" + x + "was received from the client");
            String http_verb = (String)msg_ctx.get(MessageContext.HTTP_REQUEST_METHOD);
            System.out.println(http_verb);
            String query = (String)msg_ctx.get(MessageContext.QUERY_STRING);
            System.out.println("Query String = " + query);   
            if(query == null)
            {
                System.out.println("The query variable has zero value!!!!!");
            }
            else
            {
                System.out.println("The value of the query variable is:" + query);
            }

            http_verb = http_verb.trim().toUpperCase()

        } else {
            System.out.println("Getting input from input message");
            Node n = null;
            if (request instanceof DOMSource) {
                n = ((DOMSource) request).getNode();
            } else if (request instanceof StreamSource) {
                StreamSource streamSource = (StreamSource) request;
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                InputSource inputSource = null;
                if (streamSource.getInputStream() != null) {
                    inputSource = new InputSource(streamSource.getInputStream());
                } else if (streamSource.getReader() != null) {
                    inputSource = new InputSource(streamSource.getReader());
                }
                n = db.parse(inputSource);
            } else {
                throw new RuntimeException("Unsupported source: " + request);
            }

        }

    return reply2;
    }
    catch(Exception e){
        e.printStackTrace();
        throw new HTTPException(500);
    }

}

}

客户端与服务器通信,但只有当我将参数放在URL中时,服务器才会读取参数用户名和密码:

HttpPost httppost = new HttpPost("http://10.0.2.2:8888"+"?username=" + username1 + "&password=" + password1);

服务器如何从实体主体读取参数?我正在尝试使用以下行从客户端发送参数:

UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);

传递实体主体中的参数不是更好吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作,看看它是否有效(我以前使用过它)


    StringEntity params = new StringEntity("username=" + username1 + "&password=" + password1);         
    HttpPost request = new HttpPost(path);
    HttpClient httpClient = new DefaultHttpClient();
    request.addHeader("content-type", "application/x-www-form-urlencoded");
    request.setEntity(params);

希望它也适合你。

如果您正在处理非常简单的服务器端(如您提出的问题),您可能需要查看我在下面提到的其他框架。主要看一下JAX-RS的这个代码示例:



    @POST
        @Produces(MediaType.TEXT_HTML)
        @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
        public void newTodo(
                @FormParam("id") String id,
                @FormParam("summary") String summary,
                @FormParam("description") String description,
                @Context HttpServletResponse servletResponse
        ) throws IOException {
            Todo todo = new Todo(id,summary);
            if (description!=null){
                todo.setDescription(description);
            }
            TodoDao.instance.getModel().put(id, todo);

            URI uri = uriInfo.getAbsolutePathBuilder().path(id).build();
            Response.created(uri).build();

            servletResponse.sendRedirect("../create_todo.html");
        }