httpPost方法

时间:2012-11-27 01:25:04

标签: java http http-post httpclient

我正在创建httpClient,当我发送httpPost方法时,如何将一个主体附加到httpRequest?

 public String httpPost(String URL, String BODY) {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(URL);



    try {

        response = httpclient.execute(httpPost); // get response from executing client

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            body.append(statusLine + "\n");
            HttpEntity e = response.getEntity();
            String entity = EntityUtils.toString(e);
            body.append(entity);

        } else {
            body.append(statusLine + "\n");
            // System.out.println(statusLine);
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        httpPost.releaseConnection();
    }
    return body.toString();
}

例如,字符串是
     “< html>< header> Header< / header>< body>我是身体< / body>”
我在哪里将该字符串附加到请求消息?
谢谢:))

2 个答案:

答案 0 :(得分:0)

您在尝试捕获之前尝试过httpPost.setEntity(" < html > < header > Header < /header> < body> I am body < /body> ")吗?

我不完全确定“实体”指的是什么,但这是我在查看文档 here

时能够提出的最佳结果

答案 1 :(得分:0)

您可以创建StringEntity,将其设置为HttpPost对象,然后设置正确的Content-Type

StringEntity entity = new StringEntity("data=" + java.net.URLEncoder.encode(body, "utf-8"));
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);

然后像往常一样发送你的POST请求。