1. 程式人生 > 實用技巧 >C# Post請求中Json格式寫法

C# Post請求中Json格式寫法

C#

            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/CallCenter2/CallCenter2/Ajax_GridView_Select.php");
                httpWebRequest.ContentType = "application/json;charset=utf8"; //;charset=UTF-8
                httpWebRequest.Method = "
POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"user\":\"李國林\"," + "\"password\":\"AA1122233444\"}"; streamWriter.Write(json); streamWriter.Flush(); streamWriter.Close(); }
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); } } catch (Exception ex) { MessageBox.Show(
"出錯!"+ ex.Message); }

PHP

<?php 
header("Content-Type:text/html;charset=utf8");

require_once('Log/LogHelper.php');
WriteLog('Ajax_GridView_Select---------');

foreach($_POST as $k=>$v){    
    WriteLog("POST ". $k .'--' .$v);    
}    
foreach($_GET as $k=>$v){    
    WriteLog("GET ".  $k .'--' .$v);    
}

$json_request=file_get_contents("php://input");  //取請求過來的 JSON
WriteLog( $json_request );
$arr_request = json_decode($json_request,true);
//輸出var_dump($arr);
WriteLog("arr_request0 " . $arr_request[0]);
WriteLog("arr_request1 " . $arr_request[1]);

$arr_result = array(); //返回值  

$arr_result['rows'] = "EEEEEEEEE";     
$arr_result['action'] = "黑名單"; 
//echo json_encode($arr_result );
echo encode_json($arr_result);


   //php 5.4版本之前json_encode的option裡未新增JSON_UNESCAPED_UNICODE,需自定義函式處理
   function encode_json($str)
   {
       return urldecode(json_encode(url_encode($str)));
   }
   function url_encode($str)
   {
     if(is_array($str))
      {
          foreach($str as $key=>$value)
          {
              $str[urlencode($key)] = url_encode($value);
          }
      }
      else
      {
          $str = urlencode($str);
      }
  
      return $str;
  }

?>