2012-04-20 91 views
0

我想发布一个json字符串到我的wcf服务。问题是我的WCF方法期望一个Stream对象,而不仅仅是一个JSON。用Apache HTTP客户端发送流数据到WCF

这里是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
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(); 
    } 
相关问题