使用https从WCF服务获取流



我正在尝试使用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,流结束,也许我没有正确发送或接收它。有谁能帮忙吗?

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

stream.Position = 0;

相关内容

  • 没有找到相关文章

最新更新