C# 使用HttpWebRequest實作[http post json] & [http post custom header]

C# 使用HttpWebRequest實作[http post json] & [http post custom header]

C# 使用HttpWebRequest實作[http post json] & [http post custom header]


 

資料來源:http://stackoverflow.com/questions/9145667/how-to-post-json-to-the-server

http://stackoverflow.com/questions/8519788/add-custom-header-in-httpwebrequest



code:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace CS_Console_HttpPost
{
    class Program
    {
        /*
        c# http post json
            http://stackoverflow.com/questions/9145667/how-to-post-json-to-the-server
    
        c# http post custom header    
            http://stackoverflow.com/questions/8519788/add-custom-header-in-httpwebrequest
        */
        static void Pause()
        {
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
        static void Main(string[] args)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:24408");
            httpWebRequest.ProtocolVersion = HttpVersion.Version10;//http1.0
            //httpWebRequest.Connection = "Close";
            httpWebRequest.ContentType = "text/json;charset=UTF-8";
            httpWebRequest.Method = "POST";
            httpWebRequest.Headers["API-KEY"] = "API-KEY by jash";
            httpWebRequest.ContentLength = 10000;

            StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
            string json = "{\"user\":\"test\"," +
                              "\"password\":\"bla\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
            //streamWriter.Close();
            /*
            HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream());
            String result = streamReader.ReadToEnd();
            Console.WriteLine(result);
            */

            Pause();
        }
    }
}

 

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *