JQuery, PHP, and C #

Source: Internet
Author: User

The question is a little big, but the question mentioned in this article is very small. It seems that C # is praised, but it is not.

This small problem comes from the application scenario where a third-party API is called using http post. A third-party API does not support JSON parameter passing, only parameters (a = 1 & B = 2) can be passed through the URL query string method ).

Assume that the API address is http://www.cnblogs.com/api/say. the region passed by the API is usernameand words, and only http post is supported.

In addition, add a constraint -- String concatenation is not allowed, for example, "username =" + username + "& words =" + words;

Call sample code in jQuery

var postData = {    username: 'test',    words: 'hello world'};$.ajax({    url: 'http://www.cnblogs.com/api/say',    data: postData,    type: 'post',            });

When the preceding Javascript code is executed, jQuery automatically converts the js object postData to the Url query string format (username = test & words = hello + world) and performs Url encode.

PHP call sample code

$url = 'http://www.cnblogs.com/api/say';$data = array('username' => 'test',              'words'    => 'hello world');$data = http_build_query($data); $ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response = curl_exec($ch);curl_close($ch);

PHP's built-in http_build_query () function can automatically convert arrays into Url query strings (username = test & words = hello + world) and encode URLs.

Sample Code for calling in C #

1. Implementation in. NET Framework 4.0 (HttpWebRequest + anonymous type + reflection + LINQ)

Parameters are defined by the Anonymous Type (Anonymous Type:

var postData = new{    username = "test",    words = "hello world"};

The. NET Framework 4.0 class library does not provide an API to directly convert "anonymous type instances" to "Url query parameters". It can only be implemented by "Reflection + LINQ. The implementation code is as follows:

static void Main(string[] args){    var url = "http://www.cnblogs.com/api/say";    var postData = new    {        username = "test",        words = "hello world"    };    var webRequest = WebRequest.Create(url) as HttpWebRequest;    webRequest.Method = "post";    webRequest.ContentType = "application/x-www-form-urlencoded";    var queryString = string.Join("&",                        from p in postData.GetType().GetProperties()                        select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(postData, null).ToString()));    using (var sw = new StreamWriter(webRequest.GetRequestStream()))    {        sw.Write(queryString);    }    using (var response = webRequest.GetResponse())    {        using (var sr = new StreamReader(response.GetResponseStream()))        {            Console.WriteLine(sr.ReadToEnd());        }    }}

2. Implementation in. NET Framework 4.5 (HttpClient + FormUrlEncodedContent)

. NET Framework 4.5 considers this application scenario and provides FormUrlEncodedContent, but it does not support the Anonymous Type (Anonymous Type) and only supports Dictionary ). The parameter must be defined as follows:

var postData = new Dictionary<string, string>{    { "username", "test" },    { "words", "hello world" }};

The complete implementation code is as follows (System. Net. Http must be referenced ):

static void Main(string[] args){    var url = "http://www.cnblogs.com/api/say";    var postData = new Dictionary<string, string>    {        { "username", "test" },        { "words", "hello world" }    };    var urlEncodedContent = new FormUrlEncodedContent(postData);    var httpClient = new HttpClient();    var result = httpClient.PostAsync(url, urlEncodedContent).Result.Content.ReadAsStringAsync().Result;    Console.WriteLine(result);}

The implementation in. NET Framework 4.5 is still simple, but FormUrlEncodedContent only supports Dictionary, which is not considerate.

Feelings

. NET is born on the Internet, and the request for passing parameters through URL query string is common in Internet applications. However, it is a bit difficult to say that. NET has been considering this Application Scenario since 4.5.

Many. NET developers who have developed Internet applications for many years have many years of experience in concatenating strings, but. NET does not consider this scenario. For example, double quotation marks (strings do not support the direct inclusion of double quotation marks in single quotes ). Even if you splice strings, it is not convenient to operate in Javascript and PHP.

. NET is powerful and has a leading design. However, it lacks careful consideration for Internet application scenarios. It often feels like a cool tool when using. NET to develop Internet applications. Fortunately, there is a very comfortable tool holder (Visual Studio) on the knife to attract more developers. If Internet applications are in the future, even if the hilt is more comfortable, it is not good to kill chicken with a knife. The change of the knife itself is the solution.

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.