簡體   English   中英

httpPost方法

[英]httpPost Method

我正在創建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> <標頭>標頭</標頭> <正文>我是正文</ body>”
我在哪里將該字符串附加到請求消息?
謝謝 :)

在嘗試httpPost.setEntity(" < html > < header > Header < /header> < body> I am body < /body> ")您是否嘗試過httpPost.setEntity(" < html > < header > Header < /header> < body> I am body < /body> ")

我不完全確定“實體”是指什么,但這是我從此處的文檔中可以得出的最好的結果

您可以創建一個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請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM