编辑:
我正在尝试在Android中将xml文件作为发布请求发送。
服务器接受text / xml。我尝试创建一个MultipartEntity,其内容类型为multipart / form-data。
HttpClient httpClient = new DefaultHttpClient();
/* New Post Request */
HttpPost postRequest = new HttpPost(url);
byte[] data = IOUtils.toByteArray(payload);
/* Body of the Request */
InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data), "uploadedFile");
MultipartEntity multipartContent = new MultipartEntity();
multipartContent.addPart("uploadedFile", isb);
/* Set the Body of the Request */
postRequest.setEntity(multipartContent);
/* Set Authorization Header */
postRequest.setHeader("Authorization", authHeader);
HttpResponse response = httpClient.execute(postRequest);
InputStream content = response.getEntity().getContent();
return content;
但是我收到一条错误消息,说明无法使用内容类型。
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method (Cannot consume content type).
如何更改请求的内容类型?
编辑:
答案 0 :(得分:3)
长话短说 - 为您的InputStreamBody使用另一个构造函数,允许您指定要使用的mime类型。如果不这样做,则多部分请求中的部分将不会指定Content-Type
(有关详细信息,请参阅下文)。因此,服务器不知道文件的类型,并且在您的情况下可能拒绝接受它(无论如何我接受了它们,但我认为这是由配置驱动的)。如果仍然无效,则可能存在服务器端问题。
注意:将请求本身的Content-Type
更改为multipart/form-data; boundary=someBoundary
以外的任何内容都会导致请求无效;服务器将无法正确解析多部分部分。
长篇故事 - 这是我的发现。
给出以下代码:
byte[] data = "<someXml />".getBytes();
multipartContent.addPart("uploadedFile", new InputStreamBody(new ByteArrayInputStream(data), "text/xml", "somefile.xml"));
multipartContent.addPart("otherPart", new StringBody("bar", "text/plain", Charset.forName("UTF-8")));
multipartContent.addPart("foo", new FileBody(new File("c:\\foo.txt"), "text/plain"));
HttpClient发布以下有效负载(使用Wireshark捕获):
POST /upload.php HTTP/1.1
Transfer-Encoding: chunked
Content-Type: multipart/form-data; boundary=SeXc6P2_uEGZz9jJG95v2FnK5a8ozU8KfbFYw3
Host: thehost.com
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1-alpha2 (java 1.5)
--SeXc6P2_uEGZz9jJG95v2FnK5a8ozU8KfbFYw3
Content-Disposition: form-data; name="uploadedFile"; filename="someXml.xml"
Content-Type: text/xml
Content-Transfer-Encoding: binary
<someXml />
--SeXc6P2_uEGZz9jJG95v2FnK5a8ozU8KfbFYw3
Content-Disposition: form-data; name="otherPart"
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
yo
--SeXc6P2_uEGZz9jJG95v2FnK5a8ozU8KfbFYw3
Content-Disposition: form-data; name="foo"; filename="foo.txt"
Content-Type: text/plain
Content-Transfer-Encoding: binary
Contents of foo.txt
--SeXc6P2_uEGZz9jJG95v2FnK5a8ozU8KfbFYw3--
在服务器上,使用以下PHP脚本:
<?php
print_r($_FILES);
print_r($_REQUEST);
吐出以下内容:
Array
(
[uploadedFile] => Array
(
[name] => someXml.xml
[type] => text/xml
[tmp_name] => /tmp/php_uploads/phphONLo3
[error] => 0
[size] => 11
)
[foo] => Array
(
[name] => foo.txt
[type] => text/plain
[tmp_name] => /tmp/php_uploads/php58DEpA
[error] => 0
[size] => 21
)
)
Array
(
[otherPart] => yo
)
答案 1 :(得分:0)
您可以通过这种方式上传到服务器
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(filePath), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
答案 2 :(得分:0)
我做过类似访问webservices的事情。 soap请求是一个XML请求。请参阅以下代码:
package abc.def.ghi;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
public class WebServiceRequestHandler {
public static final int CONNECTION_TIMEOUT=10000;
public static final int SOCKET_TIMEOUT=15000;
public String callPostWebService(String url, String soapAction, String envelope) throws Exception {
final DefaultHttpClient httpClient=new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);
// POST
HttpPost httppost = new HttpPost(url);
// add headers. set content type as XML
httppost.setHeader("soapaction", soapAction);
httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
String responseString=null;
try {
// the entity holds the request
HttpEntity entity = new StringEntity(envelope);
httppost.setEntity(entity);
ResponseHandler<String> rh=new ResponseHandler<String>() {
// invoked on response
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
StringBuffer out = new StringBuffer();
// read the response as byte array
byte[] b = EntityUtils.toByteArray(entity);
// write the response byte array to a string buffer
out.append(new String(b, 0, b.length));
return out.toString();
}
};
responseString=httpClient.execute(httppost, rh);
}
catch (UnsupportedEncodingException uee) {
throw new Exception(uee);
}catch (ClientProtocolException cpe){
throw new Exception(cpe);
}catch (IOException ioe){
throw new Exception(ioe);
}finally{
// close the connection
httpClient.getConnectionManager().shutdown();
}
return responseString;
}
}
答案 3 :(得分:-1)
使用您的代码,以下内容应该有效:
response.setContentType("Your MIME type");
答案 4 :(得分:-1)
无论API如何,内容类型都通过带有“Content-Type”键的标头进行协商:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
您无法控制服务所需的内容。这是他们合同的一部分。你可能正在发送'text / plain',他们期待'multipart / form-data'这个领域(想想html表单数据)。