从Android到java服务器(jetty)的httpPost请求:参数丢失了?

时间:2011-04-27 10:44:11

标签: java android http jetty http-post

我发送一个相当简单的httpPost请求,跟随this howto。 (它是德语版,但您可以查看HTTP POST示例)。这就是我得到的:

HttpPost httpPost = new HttpPost(params[0]);

HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter("title", "message");

//... setting some other parameters like http timeout, which I checked and which work 

httpPost.setParams(httpParams);

//HttpEntity myEntity = new StringEntity(messageBody);
//httpPost.setEntity(myEntity);

response = httpClient.execute(httpPost);

(评论的部分也是我尝试过的,但没有结果)。

服务器代码如下所示:

public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
    response.setContentType("text/plain;charset=utf-8");
    if (target.contentEquals("/postKdm"))
    {
        String title = request.getParameter("title");

        InputStream instream = request.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line);
        }

        System.out.println(title);

        response.setStatus(HttpServletResponse.SC_OK);
    }
}

String title和InputStream都为null / empty。我已经调试并检查了请求对象,但找不到任何看起来像我的参数。

此外,我发现了类似于我的问题here的内容,但答案对我没有多大帮助,因为我不使用Apache Camel,因此无法使用Exchange类。

哦,类似的GET请求工作非常好,但在这里我只是卡住了。 :/

我会感激任何帮助!

亲切的问候, 水母

1 个答案:

答案 0 :(得分:2)

我仍然不知道为什么“setParams”不起作用。但我使用Wireshark来检查我的传出请求,之后我找到了一个使用HttpEntity的解决方案(就像上面评论部分一样):

HttpEntity myEntity = new StringEntity(message);
httpPost.setEntity(myEntity);

response = httpClient.execute(httpPost);

服务器端我发现感谢Chris' answer,只有我当然用char缓冲区替换了字节缓冲区,如here

private String getInputString() throws IOException
{
    InputStream is = request.getInputStream();
    if (is != null)
    {

        Writer writer = new StringWriter();

        char[] buffer = new char[request.getContentLength()];

        try
        {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            int n;
            while ((n = reader.read(buffer)) != -1)
            {
                writer.write(buffer, 0, n);
            }
        }
        finally
        {
            is.close();
        }
        return writer.toString();
    }
    else
    {
        return "";
    }
}