C # Http request,

Source: Internet
Author: User

C # Http request,

String param = "<xml>"
+ "<ToUserName> <! [CDATA [toUser]> </ToUserName>"
+ "<FromUserName> <! [CDATA [fromUser]> </FromUserName>"
+ "<CreateTime> 1348831860 </CreateTime>"
+ "<MsgType> <! [CDATA [text]> </MsgType>"
+ "<Content> <! [CDATA [this is a test]> </Content>"
+ "<MsgId> 1234567890123456 </MsgId>"
+ "</Xml> ";

// Encoding format
Encoding encoding = Encoding. GetEncoding ("UTF-8 ");
Byte [] bs = encoding. GetBytes (param );

String text2 = string. Format ("http: // localhost: 52827/api/Wx ");

HttpWebRequest httpWebRequest = WebRequest. CreateHttp (text2 );
HttpWebRequest. Method = "POST ";
HttpWebRequest. ContentType = "application/x-www-form-urlencoded ";
HttpWebRequest. ContentLength = bs. Length;

Using (Stream reqStream = httpWebRequest. GetRequestStream ())
{
ReqStream. Write (bs, 0, bs. Length );
ReqStream. Flush ();
ReqStream. Close ();
}
HttpWebResponse httpWebResponse = (HttpWebResponse) httpWebRequest. GetResponse ();
HttpWebResponse response = null;
Try
{

Using (StreamReader streamReader = new StreamReader (httpWebResponse. GetResponseStream (), encoding ))
{
While (streamReader. Peek ()! =-1)
{
String text = streamReader. ReadLine () + "\ r \ n ";
}
}

}
Catch (WebException ex)
{
If (ex. Response! = Null) // incorrect status code
{
Text = (HttpWebResponse) ex. Response;

}
}
Catch (Exception ex)
{
// Other exceptions. The Status Code cannot be obtained.
Throw ex;

}

 

/// <Summary>
/// Call WebApi to obtain data
/// </Summary>
/// <Param name = "msgModel"> obtain the data of the xxx object (method name in WebApi) </param>
/// <Param name = "param"> parameter names and values to be passed </param>
/// <Returns> json data </returns>
Public static string GetMsg (string msgModel, string param)
{

If (string. IsNullOrWhiteSpace (msgModel ))
{
Return string. Empty;
}
String result = string. Empty;
String path = paietting. WEBAPI_ADDRESS + msgModel + param;
Uri resourceUri = new Uri (path );
HttpClientHandler handler = new HttpClientHandler ();
Var cts = new CancellationTokenSource ();
Cts. CancelAfter (TimeSpan. FromSeconds (300 ));
Handler. AllowAutoRedirect = false; // whether to follow the redirection
Handler. ClientCertificateOptions = ClientCertificateOption. Automatic; // use the client certificate (the certificate Storage Area of the application automatically selects the best matching certificate for verification)
Handler. UseProxy = false; // The proxy is not applicable.
Handler. usedefacrecredentials = true; // whether to use the Default User Authentication
HttpClient httpclient = new HttpClient (handler );
Httpclient. DefaultRequestHeaders. Accept. Add (new MediaTypeWithQualityHeaderValue ("application/json "));
Try
{
HttpResponseMessage response = httpclient. GetAsync (resourceUri, cts. Token). Result;
If (response. EnsureSuccessStatusCode (). IsSuccessStatusCode = true)
{
Result = response. Content. ReadAsStringAsync (). Result;
}
}
Catch (TaskCanceledException ex)
{
// Logic for canceling the request due to timeout
Result = string. Empty;
Cts. Cancel ();
Cts. Dispose ();
Handler. Dispose ();
Httpclient. Dispose ();
WriteLog ("receivetting-Class", "GetMsg", ex. Message, ex. StackTrace );
}
Catch (HttpRequestException ex)
{
// Handle other logic that may be abnormal
Result = string. Empty;
Cts. Cancel ();
Cts. Dispose ();
Handler. Dispose ();
Httpclient. Dispose ();
WriteLog ("receivetting-Class", "GetMsg", ex. Message, ex. StackTrace );
}
Catch (Exception ex)
{
// Handle other logic that may be abnormal
Result = string. Empty;
Cts. Cancel ();
Cts. Dispose ();
Handler. Dispose ();
Httpclient. Dispose ();
WriteLog ("receivetting-Class", "GetMsg", ex. Message, ex. StackTrace );
}
Return result;
}

 

 

/// <Summary>
/// Call WebApi to send post data
/// </Summary>
/// <Param name = "msgModel"> send xxx object data (method name in WebApi) </param>
/// <Param name = "jsonData"> json data to be sent </param>
/// <Param name = "paramName"> name of the parameter to be passed </param>
/// <Returns> whether the WebApi is successfully received (success/fail/error) </returns>
Public static string PostMsg (string msgModel, string jsonData, string paramName)
{
If (string. IsNullOrWhiteSpace (msgModel) // | string. IsNullOrWhiteSpace (jsonData)
{
Return string. Empty;
}

String result = string. Empty;
String path = paietting. WEBAPI_ADDRESS + msgModel + paramName;
HttpClientHandler handler = new HttpClientHandler ();
Var cts = new CancellationTokenSource ();
Cts. CancelAfter (TimeSpan. FromSeconds (300 ));
Handler. AllowAutoRedirect = false; // whether to follow the redirection
Handler. ClientCertificateOptions = ClientCertificateOption. Automatic; // use the client certificate (the certificate Storage Area of the application automatically selects the best matching certificate for verification)
Handler. UseProxy = false; // The proxy is not applicable.
Handler. usedefacrecredentials = true; // whether to use the Default User Authentication
HttpClient httpclient = new HttpClient (handler );
Httpclient. DefaultRequestHeaders. Accept. Add (new MediaTypeWithQualityHeaderValue ("application/json "));
Try
{
Uri resourceUri = new Uri (path + jsonData );
// HttpResponseMessage response = httpclient. GetAsync (resourceUri, cts. Token). Result;
HttpResponseMessage response = httpclient. PostAsync (resourceUri, new StringContent (jsonData), cts. Token). Result;
If (response. EnsureSuccessStatusCode (). IsSuccessStatusCode = true)
{
Result = response. Content. ReadAsStringAsync (). Result;
}
}
Catch (TaskCanceledException ex)
{
// Logic for canceling the request due to timeout
Result = string. Empty;
Cts. Cancel ();
Cts. Dispose ();
Handler. Dispose ();
Httpclient. Dispose ();
WriteLog ("receivetting-Class", "PostMsg", ex. Message, ex. StackTrace );
}
Catch (HttpRequestException ex)
{
// Handle other logic that may be abnormal
Result = string. Empty;
Cts. Cancel ();
Cts. Dispose ();
Handler. Dispose ();
Httpclient. Dispose ();
WriteLog ("receivetting-Class", "PostMsg", ex. Message, ex. StackTrace );
}
Catch (Exception ex)
{
// Handle other logic that may be abnormal
Result = string. Empty;
Cts. Cancel ();
Cts. Dispose ();
Handler. Dispose ();
Httpclient. Dispose ();
WriteLog ("receivetting-Class", "PostMsg", ex. Message, ex. StackTrace );
}
Return result;
}

Public string PostXml (string url, string strPost)
{
String result = "";

StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest) WebRequest. Create (url );
ObjRequest. Method = "POST ";
// ObjRequest. ContentLength = strPost. Length;
ObjRequest. ContentType = "text/xml"; // submit xml
// ObjRequest. ContentType = "application/x-www-form-urlencoded"; // submit the form
Try
{
MyWriter = new StreamWriter (objRequest. GetRequestStream ());
MyWriter. Write (strPost );
}
Catch (Exception e)
{
Return e. Message;
}
Finally
{
MyWriter. Close ();
}

HttpWebResponse objResponse = (HttpWebResponse) objRequest. GetResponse ();
Using (StreamReader sr = new StreamReader (objResponse. GetResponseStream ()))
{
Result = sr. ReadToEnd ();
Sr. Close ();
}
Return result;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.