2012-11-27 60 views
0

我正在創建httpClient,並且當我發送httpPost方法時,如何將一個主體附加到httpRequest?httpPost方法

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>」
哪裏該字符串附加到所述請求消息?
謝謝:)

回答

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請求如常。

0

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

我不能完全確定什麼是「實體」是指,但這是我能拿出從看文檔here

+2

setEntity方法僅需要實體...我想知道如何將字符串解析爲實體.. – Ken