如何避免UriFormatException?

时间:2014-09-01 14:00:35

标签: .net rest httpwebrequest compact-framework webrequest

我在Windows Mobile平台cf3.5上有一个应用程序。这与Web服务器通信,他们做得很好,请求得到正确的回复。 但是,在每个请求中,它都会在visual studio输出窗口中抛出System.UriFormatException。 Uris看起来像这样:

http://api/Information/TagKey/4952b9ff-af55-4219-95b8-1ac57a70b7a8/L0011421

我怎么知道这些uris有什么问题?我应该改变' - ' guid领域的chars还是什么?

我通过这种方法构建uri,其中uri是服务器的基地址,字典包含参数:

private static string buildUri(string uri, Dictionary<string, string> data)
    {
        StringBuilder _uri = new StringBuilder(uri);
        foreach(KeyValuePair<string, string> item in data) 
        {
            _uri.Append("/" + item.Value);
        }
        return _uri.ToString();
    }

这个createRequest方法使用它:

private static HttpWebRequest createRequest(string uri, HttpMethods method, Dictionary<string, string> data, Dictionary<string, object> postdata)
    {
        string fullUri = buildUri(uri, data);
        Classes.Log.Write("/// "+fullUri);
        WebRequest request = HttpWebRequest.Create(fullUri);
        request.Method = Enum.ToObject(typeof(HttpMethods), method).ToString();
        request.ContentType = "application/json; charset=utf-8";
        ((HttpWebRequest)request).Accept = "application/json; charset=utf-8";
        request.ContentLength = 0;
        if (method != HttpMethods.GET && method != HttpMethods.DELETE && postdata != null)
        {
            Encoding encoding = Encoding.UTF8;
            string postData = buildPostData(postdata, "application/json");
            byte[] byteArray = encoding.GetBytes(postData);
            request.ContentLength = byteArray.Length;
            if (byteArray != null && byteArray.Length > 0)
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(byteArray, 0, (int)request.ContentLength);
                }
            }
        }
        return (HttpWebRequest)request;
    }

它会抛出异常

WebResponse response = request.GetResponse();

这是另一种方法。

我首先通过字符串生成了一个Uri对象,它不会抛出任何异常。

0 个答案:

没有答案