C# でリモート HTTP ポスト (リクエスト) を行うにはどうすればよいですか?
17959 次
8 に答える
11
これは、値を含むフォームを URL に投稿するために私が一度書いた小さなアプリのコードです。かなり堅牢なはずです。
_formValues は、投稿する変数とその値を含む Dictionary<string,string> です。
// encode form data
StringBuilder postString = new StringBuilder();
bool first=true;
foreach (KeyValuePair pair in _formValues)
{
if(first)
first=false;
else
postString.Append("&");
postString.AppendFormat("{0}={1}", pair.Key, System.Web.HttpUtility.UrlEncode(pair.Value));
}
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] postBytes = ascii.GetBytes(postString.ToString());
// set up request object
HttpWebRequest request;
try
{
request = WebRequest.Create(url) as HttpWebRequest;
}
catch (UriFormatException)
{
request = null;
}
if (request == null)
throw new ApplicationException("Invalid URL: " + url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
// add post data to request
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
于 2009-02-13T20:22:27.237 に答える
4
WCF を使用するか、WebRequest を作成できます
var httpRequest = (HttpWebRequest)WebRequest.Create("http://localhost/service.svc");
var httpRequest.Method = "POST";
using (var outputStream = httpRequest.GetRequestStream())
{
// some complicated logic to create the message
}
var response = httpRequest.GetResponse();
using (var stream = response.GetResponseStream())
{
// some complicated logic to handle the response message.
}
于 2009-02-13T19:37:41.260 に答える
4
私はこの非常に単純なクラスを使用します:
public class RemotePost{
private System.Collections.Specialized.NameValueCollection Inputs
= new System.Collections.Specialized.NameValueCollection() ;
public string Url = "" ;
public string Method = "post" ;
public string FormName = "form1" ;
public void Add( string name, string value ){
Inputs.Add(name, value ) ;
}
public void Post(){
System.Web.HttpContext.Current.Response.Clear() ;
System.Web.HttpContext.Current.Response.Write( "<html><head>" ) ;
System.Web.HttpContext.Current.Response.Write( string .Format( "</head><body onload=\"document.{0}.submit()\">" ,FormName)) ;
System.Web.HttpContext.Current.Response.Write( string .Format( "<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >" ,
FormName,Method,Url)) ;
for ( int i = 0 ; i< Inputs.Keys.Count ; i++){
System.Web.HttpContext.Current.Response.Write( string .Format( "<input name=\"{0}\" type=\"hidden\" value=\"{1}\">" ,Inputs.Keys[i],Inputs[Inputs.Keys[i]])) ;
}
System.Web.HttpContext.Current.Response.Write( "</form>" ) ;
System.Web.HttpContext.Current.Response.Write( "</body></html>" ) ;
System.Web.HttpContext.Current.Response.End() ;
}
}
そして、あなたはそれを次のように使用します:
RemotePost myremotepost = new RemotePost() ;
myremotepost.Url = "http://www.jigar.net/demo/HttpRequestDemoServer.aspx" ;
myremotepost.Add( "field1" , "Huckleberry" ) ;
myremotepost.Add( "field2" , "Finn" ) ;
myremotepost.Post() ;
非常にきれいで使いやすく、汚れをすべてカプセル化します。HttpWebRequest などを直接使用するよりも、これをお勧めします。
于 2009-02-13T19:37:54.007 に答える
2
を使用してプロパティWebRequest.Create()
を設定しMethod
ます。
于 2009-02-13T19:39:22.893 に答える
2
またSystem.Net.WebClient
于 2009-02-13T19:43:07.893 に答える
1
httpwebrequestクラスを使用してWebサービスを呼び出すために次のコードを使用しています。
internal static string CallWebServiceDetail(string url, string soapbody,
int timeout) {
return CallWebServiceDetail(url, soapbody, null, null, null, null,
null, timeout);
}
internal static string CallWebServiceDetail(string url, string soapbody,
string proxy, string contenttype, string method, string action,
string accept, int timeoutMilisecs) {
var req = (HttpWebRequest) WebRequest.Create(url);
if (action != null) {
req.Headers.Add("SOAPAction", action);
}
req.ContentType = contenttype ?? "text/xml;charset=\"utf-8\"";
req.Accept = accept ?? "text/xml";
req.Method = method ?? "POST";
req.Timeout = timeoutMilisecs;
if (proxy != null) {
req.Proxy = new WebProxy(proxy, true);
}
using(var stm = req.GetRequestStream()) {
XmlDocument doc = new XmlDocument();
doc.LoadXml(soapbody);
doc.Save(stm);
}
using(var resp = req.GetResponse()) {
using(var responseStream = resp.GetResponseStream()) {
using(var reader = new StreamReader(responseStream)) {
return reader.ReadToEnd();
}
}
}
}
これは、Webサービスを呼び出すために簡単に使用できます
public void TestWebCall() {
const string url =
"http://www.ecubicle.net/whois_service.asmx/HelloWorld";
const string soap =
@"<soap:Envelope xmlns:soap='about:envelope'>
<soap:Body><HelloWorld /></soap:Body>
</soap:Envelope>";
string responseDoc = CallWebServiceDetail(url, soap, 1000);
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseDoc);
string response = doc.DocumentElement.InnerText;
}
于 2009-03-26T12:10:14.337 に答える
0
HttpWebRequest HttpWReq =
(HttpWebRequest)WebRequest.Create("http://www.google.com");
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
Console.WriteLine(HttpWResp.StatusCode);
HttpWResp.Close();
リクエストが成功した場合、「OK」(200)を出力する必要があります
于 2009-02-13T19:42:41.547 に答える
-3
C#、Java、PHP などの高水準言語から始める場合の問題は、アンダーグラウンドが実際にどれほど単純であるかを人々が知らなかった可能性があることです。それでは、簡単に紹介します。
于 2009-08-16T21:11:49.733 に答える