2009-05-25 18 views
11

ile "URI formatı belirlenemedi" C# içinde bir WebRequest kullanarak bir siteye POST gerçekleştirmeye çalışıyorum. Gönderdiğim site bir SMS sitesidir ve messagetext URL'nin bir parçasıdır. URL'de boşluklardan kaçınmak için URL'yi kodlamak için HttpUtility.Encode() öğesini arıyorum.WebRequest

Ama ben URIFormatException almaya devam - "geçersiz URI: URI biçimi belirlenemedi" - Ben buna benzer bir kod kullandığınızda: dediğim zaman

string url = "http://www.stackoverflow.com?question=a sentence with spaces"; 
string encoded = HttpUtility.UrlEncode(url); 

WebRequest r = WebRequest.Create(encoded); 
r.Method = "POST"; 
r.ContentLength = encoded.Length; 
WebResponse response = r.GetResponse(); 

durum oluşur WebRequest.Create().

Neyi yanlış yapıyorum?

cevap

16

Yalnızca argüman değil, tüm url kodlamak, bu yüzden denemelisiniz:

string url = "http://www.stackoverflow.com?question=" + HttpUtility.UrlEncode("a sentence with spaces"); 

WebRequest r = WebRequest.Create(url); 
r.Method = "POST"; 
r.ContentLength = encoded.Length; 
WebResponse response = r.GetResponse(); 

tüm url anlamına geleceğini Kodlama: // ve? kodlanmış olsun. Kodlanmış dize artık geçerli bir URL değildir.

+0

[Bu SO kaydı] bölümünde (http://stackoverflow.com/a/1148326/5838198) açıklandığı gibi, 'HttpUtility' veya' Server 'yöntemleri yerine 'Uri.EscapeDataString()' işlevini kullanmak en iyisidir . – Siavas

1

UrlEncode yalnızca sorgu dizesinde kullanılmalıdır. Bu deneyin:

string query = "a sentence with spaces"; 
string encoded = "http://www.stackoverflow.com/?question=" + HttpUtility.UrlEncode(query); 

kodunuzun geçerli sürümü WebRequest kafa karıştırıcı URL içinde eğik çizgi ve iki nokta üst üste URL kodlamasından edilir.

İlgili konular