Java 使用Android发布XML文件
编辑: 我试图在Android中发送一个xml文件作为post请求 服务器接受text/xml。我尝试创建一个MultipartEntity,其内容类型为multipart/formdataJava 使用Android发布XML文件,java,android,apache,httpclient,http-post,Java,Android,Apache,Httpclient,Http Post,编辑: 我试图在Android中发送一个xml文件作为post请求 服务器接受text/xml。我尝试创建一个MultipartEntity,其内容类型为multipart/formdata HttpClient httpClient = new DefaultHttpClient(); /* New Post Request */ HttpPost postRequest = new HttpPost(url); byte[] data = IOUtils.toB
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).
如何更改请求的内容类型?
编辑:使用您的代码,以下内容应该可以工作:
response.setContentType("Your MIME type");
无论API如何,内容类型都是通过带有“content type”键的标头协商的:
您无法控制服务的期望值。这是他们合同的一部分。您可能正在发送“text/plain”,而他们希望在“multipart/form data”(想想html表单数据)领域中有一些内容。长话短说-为您的InputStreamBody使用另一个构造函数,该构造函数允许您指定要使用的mime类型。如果不指定,则多部分请求中的部分将不会指定
内容类型
(有关详细信息,请参见下文)。因此,服务器不知道文件的类型,在您的情况下,可能会拒绝接受它(我的服务器还是接受了它们,但我认为这是由配置驱动的)。如果这仍然不起作用,您可能会遇到服务器端问题
注意:将请求本身的内容类型
更改为除多部分/表单数据以外的任何内容;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 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);
我做了一些类似于访问Web服务的事情。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;
}
}
包abc.def.ghi;
导入java.io.IOException;
导入java.io.UnsupportedEncodingException;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.ResponseHandler;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.entity.StringEntity;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.params.HttpConnectionParams;
导入org.apache.http.params.HttpParams;
导入org.apache.http.params.HttpProtocolParams;
导入org.apache.http.util.EntityUtils;
公共类WebServiceRequestHandler{
公共静态最终int连接\u超时=10000;
公共静态最终int套接字超时=15000;
公共字符串callPostWebService(字符串url、字符串soapAction、字符串信封)引发异常{
final DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpParams params=httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(参数,连接超时);
HttpConnectionParams.setSoTimeout(参数,套接字超时);
HttpProtocolParams.setUseExpectContinue(httpClient.getParams(),true);
//职位
HttpPost HttpPost=新的HttpPost(url);
//添加标题。将内容类型设置为XML
setHeader(“soapaction”,soapaction);
setHeader(“内容类型”,“text/xml;charset=utf-8”);
字符串responseString=null;
试一试{
//实体持有请求
HttpEntity实体=新的StringEntity(信封);
httppost.setEntity(实体);
ResponseHandler rh=新ResponseHandler(){
//响应时调用
公共字符串句柄响应(HttpResponse响应)
抛出ClientProtocolException,IOException{
HttpEntity=response.getEntity();
StringBuffer out=新的StringBuffer();
//将响应读取为字节数组
字节[]b=EntityUtils.toByteArray(实体);
//将响应字节数组写入字符串缓冲区
append(新字符串(b,0,b.length));
return out.toString();
}
};
responseString=httpClient.execute(httppost,右侧);
}
捕获(不支持的编码异常uee){
抛出新异常(uee);
}捕获(客户端协议异常cpe){
抛出新异常(cpe);
}捕获(ioe异常ioe){
抛出新异常(ioe);
}最后{
//关闭连接
httpClient.getConnectionManager().shutdown();
}
回报率;
}
}
我需要更改请求的内容类型。您想将其更改为什么?它现在是什么?为什么服务器不支持它?如果您发送xml,您使用MultipartEntity有什么具体原因吗?@Lauri。我想我也会派一个线人去。是否有更简单的方法只发送XML文件?您希望服务器接收XML文件还是仅接收XML内容?告诉编写服务器的人,他们应该使用PUT
,而不是POST
,来提交文本/XML
内容。我认为在这种情况下更适用,多部分请求可以指定多个内容类型。我还认为HttpClient会检测并设置附加文件的正确类型。但在这里…我会为您搜索它:call setParameter(“Content Type”,“theexpected/Type”)不。不走运。服务器仍然拒绝我的输入。有什么方法可以发送XML内容而不使其成为多部分的吗?XML是纯文本,您可以使用StringEntity而不是MultipartEntity。想试试你的Android代码,看看它输出了什么(这就是我测试的页面)?嗨,劳里。非常感谢你帮助我。有时我对互联网的力量感到惊讶。无论如何,我只能投你一票,给你一些分数。但是字符串实体像一个符咒一样工作。再次感谢你。但愿我能做更多的事来表达我的感激之情。:)@Foysal upload.php刚刚包含了php
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
)
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);
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;
}
}