【问题标题】:httpPost MethodhttpPost 方法
【发布时间】:2012-11-27 01:25:04
【问题描述】:

我正在创建 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();
}

例如,字符串是
"

Header

我是body "
在哪里将该字符串附加到请求消息中?
谢谢你:)

【问题讨论】:

    标签: java http http-post httpclient


    【解决方案1】:

    您可以创建一个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 请求。

    【讨论】:

      【解决方案2】:

      在 try-catch 之前您是否尝试过 httpPost.setEntity(" < html > < header > Header < /header> < body> I am body < /body> ")

      我不完全确定“实体”指的是什么,但这是我通过查看文档可以得出的最佳结论 here

      【讨论】:

      • setEntity 方法只接受实体...我想知道如何将字符串解析为实体..
      猜你喜欢
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      • 2023-03-16
      • 2011-10-04
      相关资源
      最近更新 更多