【问题标题】:Get a stream from WCF service with https使用 https 从 WCF 服务获取流
【发布时间】:2014-04-20 19:15:15
【问题描述】:

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

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

上面是获取图片方法的定义,下面是实现(我从附件数据列中包含的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,流结束,也许我没有正确发送或接收它。有什么帮助吗?

【问题讨论】:

    标签: c# android wcf stream


    【解决方案1】:

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

    stream.Position = 0;
    

    【讨论】:

      猜你喜欢
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-05
      • 2011-08-03
      • 1970-01-01
      • 2012-02-18
      相关资源
      最近更新 更多