2012-04-20 81 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(); 
    }