使用https从WCF服务获取流

时间:2014-03-15 11:02:57

标签: c# android wcf stream

我正在尝试使用Android客户端从我的wcf服务下载图像。连接是用ssl保护的,所以我必须给予特殊权限才能执行此操作。我不确定这是否可以,但这就是我所拥有的:

 [OperationContract]
    [WebGet(UriTemplate="getstream")]
    Stream GetStream();

上面是获取图片的方法的定义,下面是实现(我从AttachmentData列中包含的sql server中的varbinary字段获取图像)。

public Stream GetStream()
    {
        using (MojDBEntities ctx = new MojDBEntities())
        {
            var image = from attach in ctx.JournalAttachments
                        where attach.JournalAttachmentID == 747
                        select attach;

            List<JournalAttachment> ls = image.ToList();
            JournalAttachment temp = ls.ElementAt(0);
            byte[] myByteArray = temp.AttachmentData;
            MemoryStream stream = new MemoryStream(); 
            stream.Write(myByteArray, 0, myByteArray.Length);
            return stream;
        }
    }

在android方面,我首先使用此代码来信任任何ssl证书:

    public void TrustALL() throws IOException, NoSuchAlgorithmException, KeyManagementException{
    TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    }
};

// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
};

// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

}

最后获得流:

TrustALL();
            URL imageUrl = new URL("https://192.168.10.103/RcaRestService/RCAService.svc/getstream");
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();

            Log.i("donnnn", ""+is.read());

问题是我立即得到-1,流的结尾,也许我没有发送它或接收它。有人帮忙吗?

1 个答案:

答案 0 :(得分:0)

我通过在从WCF返回之前重置流位置来解决这个问题:

stream.Position = 0;