search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

C# 使用HttpWebRequest實作[http post json] & [http post custom header] – jashliao部落格

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

 

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();
        }
    }
}

 

 

 



熱門推薦

本文由 jashliaoeuwordpress 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦