繁体   English   中英

使用Android发布XML文件

[英]Using Android to Post XML files

编辑:

我正在尝试发送xml文件作为Android中的发布请求。

服务器接受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).

如何更改请求的内容类型?

编辑:

长话短说- 为InputStreamBody使用另一个构造函数,使您可以指定要使用的mime类型 如果您没有这样做,则您的multipart请求中的部分将不会指定Content-Type (有关详细信息,请参见下文)。 因此,服务器不知道文件是什么类型,并且在您的情况下可能拒绝接受它(无论如何我都接受了它们,但是我认为这是由config驱动的)。 如果仍然无法解决问题,则可能是服务器端出现问题。

注意:将请求本身的Content-Type更改为multipart/form-data; boundary=someBoundary任何内容multipart/form-data; boundary=someBoundary 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
)

您可以通过这种方式上传到服务器

        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;
    }

}

使用您的代码,以下应该可以工作:

response.setContentType("Your MIME type");

无论使用哪种API,都通过带有“ Content-Type”键的标头协商内容类型:

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

您无法控制服务的期望。 这是他们合同的一部分。 您可能正在发送“文本/纯文本”,他们期望在“ multipart / form-data”(例如html表单数据)领域中有所收获。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM