1. 程式人生 > >HttpClient 呼叫web Api 傳遞json引數

HttpClient 呼叫web Api 傳遞json引數

1.在使用HttpClient 的時候需要引用system.net.http;
2.system.net.http引用是.net4.5框架引入的一個方式,所以使用的時候要確保專案是.net 4.5 或更高版本
  1. 程式碼如下:

     static void Main(string[] args)
    {
        httpclient();
    }
      public static void httpclient()
    {
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        string url = "http://192.168.0.86:8585/gsa/tool/es/selAndImportData";
        var json = "{\"dataSource\":\"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.0.70)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl70)));User ID=sde;Password=sde;Unicode=True\",\"type\":\"0\",\"whereCondition\":\"dlwz='國和百壽一村6號'\",\"tableName\":\"hzdzd_pt\"}";
    
    
      //  var json = "{ \"dataSource\": \"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.0.70)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl70)));User ID=sde;Password=sde;Unicode=True\" }";
        var httpContent = new StringContent(json, Encoding.UTF8);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var response = client.PostAsync(url, httpContent).Result;
        Console.WriteLine(response.Content);
        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.StatusCode);
            Console.ReadLine();
            //Response (string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase));
        }
    }