0

我正在尝试将 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 完成,因为我有使用它的自定义身份验证代码。

4

1 回答 1

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();
    }
于 2012-12-14T20:38:29.037 回答