2013-02-05 3 views
70

양식 데이터를 내 웹 응용 프로그램 내에 있지 않은 지정된 URL에 게시하고 싶습니다. 도메인은 "domain.client.nl"과 같습니다. 웹 응용 프로그램에는 "web.domain.client.nl"이라는 url이 있습니다.이 URL은 "idp.domain.client.nl"입니다. 하지만 내 코드는 아무 것도하지 않습니다 ..... 누군가 내가 뭘 잘못하고 있는지 알고 있습니까?HttpWebRequest를 사용하여 양식 데이터 게시

WOUTER

StringBuilder postData = new StringBuilder(); 
postData.Append(HttpUtility.UrlEncode(String.Format("username={0}&", uname))); 
postData.Append(HttpUtility.UrlEncode(String.Format("password={0}&", pword))); 
postData.Append(HttpUtility.UrlEncode(String.Format("url_success={0}&", urlSuccess))); 
postData.Append(HttpUtility.UrlEncode(String.Format("url_failed={0}", urlFailed))); 

ASCIIEncoding ascii = new ASCIIEncoding(); 
byte[] postBytes = ascii.GetBytes(postData.ToString()); 

// set up request object 
HttpWebRequest request; 
try 
{ 
    request = (HttpWebRequest)HttpWebRequest.Create(WebSiteConstants.UrlIdp); 
} 
catch (UriFormatException) 
{ 
    request = null; 
} 
if (request == null) 
    throw new ApplicationException("Invalid URL: " + WebSiteConstants.UrlIdp); 

request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 
request.ContentLength = postBytes.Length; 
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; 

// add post data to request 
Stream postStream = request.GetRequestStream(); 
postStream.Write(postBytes, 0, postBytes.Length); 
postStream.Flush(); 
postStream.Close(); 
+0

가능한 중복 : http://stackoverflow.com/questions/5401501/how-to-post-data-to-specific-url-using-webclient-in-c-sharp – Dariusz

+4

하지 않음 확실히 다른 하나는'WebClient'를 사용하려고합니다. –

답변

34

양식을 잘못 인코딩된다. 당신은 단지 값을 인코딩해야합니다

StringBuilder postData = new StringBuilder(); 
postData.Append("username=" + HttpUtility.UrlEncode(uname) + "&"); 
postData.Append("password=" + HttpUtility.UrlEncode(pword) + "&"); 
postData.Append("url_success=" + HttpUtility.UrlEncode(urlSuccess) + "&"); 
postData.Append("url_failed=" + HttpUtility.UrlEncode(urlFailed)); 

편집

내가 잘못했다. RFC1866 section 8.2.1에 따르면 이름과 값을 모두 인코딩해야합니다.

그러나

이 경우 내 코드 예제가 올바른지에 있도록 주어진 예를 들어, 이름은 인코딩 할 필요가있는 문자가없는, 그것은 인코딩하는 것처럼 문제의

코드는 여전히 올바르지 않습니다) 웹 서버가 디코딩 할 수없는 이유 인 등호.

더 적절한 방법이었을 것입니다 :

StringBuilder postData = new StringBuilder(); 
postData.AppendUrlEncoded("username", uname); 
postData.AppendUrlEncoded("password", pword); 
postData.AppendUrlEncoded("url_success", urlSuccess); 
postData.AppendUrlEncoded("url_failed", urlFailed); 

//in an extension class 
public static void AppendUrlEncoded(this StringBuilder sb, string name, string value) 
{ 
    if (sb.Length != 0) 
     sb.Append("&"); 
    sb.Append(HttpUtility.UrlEncode(name)); 
    sb.Append("="); 
    sb.Append(HttpUtility.UrlEncode(value)); 
} 
+0

고마워, butnow 다음 오류가 발생합니다. 원격 서버에서 오류를 반환했습니다. (412) Precondition Failed. – wsplinter

+0

Google에 게시 했습니까? – jgauffin

+0

나는 구글을 많이 :) 그러나 나는 그것을 고쳤다. 나는 더러 트리 방식으로하고있다. 나는 HttpWebRequest를하지 않지만 String과 hirt 안에 html 폼을 만들어 브라우저에 보낸다. (onload에서 submit을 할 것이다.) – wsplinter

61

필드 이름 모두와 값은 URL 인코딩해야합니다. 포스트 데이터와 쿼리 문자열의 형식은 같은

일의 .NET 방법이

NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty); 
outgoingQueryString.Add("field1","value1"); 
outgoingQueryString.Add("field2", "value2"); 
string postdata = outgoingQueryString.ToString(); 

이 같은 것이 필드와 값 이름

+8

'string postdata = outgoingQueryString.ToString();'은 값 "System.Collections.Specialized.NameValueCollection"으로 문자열을 제공합니다. – sfuqua

+1

실제로 당신이 HttpUtility (특히 System.Web에있는 소스)에 대한 소스를 디 컴파일하면 특별한 NameValueCollection 유형을 반환한다는 것을 알 수 있습니다 : return (NameValueCollection) new HttpValueCollection (query, false, true, encoding); 컬렉션을 쿼리 문자열로 올바르게 변환합니다. 그러나 RestSharp에서 사용하는 경우에는 그렇지 않습니다. –

+0

흥미 롭습니다. ToString()을 사용하여 정확한 문제를 보았으므로 RestSharp를 사용하는 동안 기억이 안납니다. 확실한 가능성. 수정 해줘서 고마워. – sfuqua

35

시도를 인코딩 처리됩니다입니다 이 :

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx"); 

var postData = "thing1=hello"; 
    postData += "&thing2=world"; 
var data = Encoding.ASCII.GetBytes(postData); 

request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 
request.ContentLength = data.Length; 

using (var stream = request.GetRequestStream()) 
{ 
    stream.Write(data, 0, data.Length); 
} 

var response = (HttpWebResponse)request.GetResponse(); 

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 
+2

같은 매력, ​​덕분 근무 :) –

+2

나는 차라리 작성 : request.Method = WebRequestMethods.Http.Post; – Totalys

+0

확인 요청. 응답 사용 전 응답 –

관련 문제