0

我正在创建 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>I am body</body>”
我在哪里将该字符串附加到请求消息中?
谢谢 :)

4

2 回答 2

0

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

我不完全确定“实体”指的是什么,但这是我通过查看此处的文档所能想到的最好的

于 2012-11-27T01:36:53.300 回答
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 请求。

于 2012-11-27T01:39:05.743 回答