使用Apache HTTP客户端将流数据发布到WCF

时间:2012-04-20 17:52:05

标签: android json wcf httpclient

我正在尝试将json字符串发布到我的wcf服务中。问题是我的WCF方法需要Stream对象而不仅仅是JSON。

以下是WCF中的方法标题:

    [WebInvoke(Method = "POST", UriTemplate = "person/delete", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Person DeletePerson(Stream streamdata)

以下是我一直在尝试的内容:

    HttpPost request = new HttpPost(SERVICE_URI + uri);
    InputStream is = new ByteArrayInputStream(data.getBytes());
    InputStreamEntity ise = new InputStreamEntity(is, data.getBytes().length);
    ise.setContentType("application/x-www-form-urlencoded");
    ise.setContentEncoding(HTTP.UTF_8);
    request.setEntity(ise);
    HttpResponse response = null;
    try {
        response = client.execute(request);
    } catch (ClientProtocolException e) 
    {
        e.printStackTrace();
    } catch (IOException e) 
    {
        e.printStackTrace();
    }

我得到了400个错误的请求以及我尝试的其他一切。有人可以帮助我让这个工作!?此外,它必须使用HttpClient完成,因为我有自定义身份验证代码。

1 个答案:

答案 0 :(得分:4)

HttpPost request = new HttpPost(SERVICE_URI + uri);
    AbstractHttpEntity entity = new AbstractHttpEntity() {
        public boolean isRepeatable() { return true; }
        public long getContentLength() { return -1; }
        public boolean isStreaming() { return false; }
        public InputStream getContent() throws IOException { throw new     UnsupportedOperationException(); }
        public void writeTo(final OutputStream outstream) throws IOException {
            Writer writer = new OutputStreamWriter(outstream, "UTF-8");
            writer.write(arr, 0, arr.length);
            writer.flush();
        }
    };

    entity.setContentType("application/x-www-form-urlencoded");
    entity.setContentEncoding(HTTP.UTF_8);
    request.setEntity(entity);
    HttpResponse response = null;
    InputStream bais = null;
    String result = null;
    try {
        response = client.execute(request);
        HttpEntity he = response.getEntity();
        bais = he.getContent();
        result = convertStreamToString(bais);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    }