2012-11-27 34 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