0

我需要将一些 XML 发送到 web 服务,并且我能够使用普通的 StringEntity 来完成它,因为它只是文本,但现在我还需要将图像附加到它。我尝试使用 MultipartEntity 进行操作,但无法仅使用 XML。

// 在职的

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

3 回答 3

4

你只是忘记了:

httppost.setEntity(entity);

顺便说一句,设置零件的 Content-Type 可能是一种很好的形式,例如:

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

至于查看正在发送的内容,请参阅http://hc.apache.org/httpcomponents-client-ga/logging.html(尤其是“线路日志”)以了解 HttpClient 日志记录功能,以及 如何使其工作的这个问题在安卓上。

于 2011-03-29T15:32:21.520 回答
1

另一种查看发送内容的方法是设置您自己的“服务器”来接收请求。您可以使用 netcat 在类 Unix 系统上执行此操作。命令行

nc -l 1234

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

如果该“服务器”在机器 10.1.2.3 上,您可以使用 anew HttpPost("http://10.1.2.3:1234")在那里发送消息。

于 2011-03-31T14:08:24.767 回答
0

我有一个类似的问题,但我将带有用户/密码的多部分发送到 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);
}
于 2011-05-19T14:01:58.127 回答