2011-03-29 71 views
0

我需要一些XML发送到Web服务,我能够与正常StringEntity这样做,因为它只是文字,但现在我需要的图像附加到它。我试着用MultipartEntity做这件事,但是我不能用它来处理XML。MultipartEntity没有创造良好的请求

//工作

DefaultHttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost doc = new HttpPost("http://mywebservices.com"); 

HttpEntity entity = new StringEntity(writer.toString()); 
httppost.setEntity(entity); 

HttpResponse response = httpclient.execute(httppost); 
HttpEntity responseEntity = response.getEntity(); 

//不工作

DefaultHttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost doc = new HttpPost("http://mywebservices.com"); 

// no difference when removing the BROWSER_COMPATIBLE 
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
entity.addPart("xml", new StringBody(writer.toString())); 
httppost.setEntity(entity); 

HttpResponse response = httpclient.execute(httppost); 
HttpEntity responseEntity = response.getEntity(); 

,是有办法,我可以看到正在发送的MIME?

回答

4

你根本忘了:

httppost.setEntity(entity); 

顺便说一句,这是件好事形式来设置部件的内容类型,如:

entity.addPart("xml", new StringBody(writer.toString(),"application/xml",Charset.forName("UTF-8"))); 

至于看到东西被发送到了什么,请参阅HttpClient的日志记录功能http://hc.apache.org/httpcomponents-client-ga/logging.html(尤其是“丝日志”),并 this question如何得到它在Android上工作。

+0

哦我看到我忘了复制'httppost.setEntity(实体);',它在我的代码,但没有工作:( – 2011-03-29 17:34:34

+0

嗯,你说这是行不通的,究竟是什么出了问题 – 2011-03-30 20:35:49

+0

web服务是?无法读取请求并给我一个错误,所以'MultipartEntity'产生的另一个帖子比正常的'HttpEntity',但我无法看到帖子。 – 2011-03-31 07:55:46

1

另一种方式看东西被发送到了什么是建立自己的“服务器”接收请求。你可以在一个类似于Unix的系统上使用netcat来做到这一点。命令行

nc -l 1234 

启动一个侦听端口1234的服务器,并将回应接收到的任何内容。

如果“服务器”是一台机器10.1.2.3上,你可以只使用一个new HttpPost("http://10.1.2.3:1234")那里发送邮件。

+0

哇,这是非常有用的 – 2011-04-02 15:12:52

+0

有点此外,如果你想这样做在Windows上,你可以在这里下载http://www.securityfocus.com/tools/139和NetCat的,你应该像这样运行它。 'C:\ path \ to \ nc.exe -l -p 1234' – 2011-08-02 08:53:44

0

我有一个类似的问题,但我将与用户的multipart /传递给Acegi安全系统,其工作原理与此:

request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 

但不与本:

try { 
    for (NameValuePair param : params) { 
     multientity.addPart(param.getName(), new StringBody(param.getValue(),  Charset.forName(encoding)))); 
    } 
    request.setEntity(multientity); 
} 
+0

您意味着问题的答案是第一块代码? – Alfabravo 2015-01-09 16:34:18