如何将PHP cURLcode转换为C#

时间:2017-04-28 07:00:24

标签: c#

我没有任何PHP经验,但我需要创建与此代码等效的C#:

<?php

$config['Api-key'] = 'UQ042222gh3TZJ6AWrLB';

$config['Api-secret'] ='UQ042222-RTSmc8ROnCMyNVXnYn9eXAVGi7JhOoug0RTL';

$config['Api-url']  =   'https://uquid.com/api/';

function connectToApi( $endpoint='', $fields = array() )
{   
global $config;  
$ch = curl_init();     
$url =$config['Api-url'].$endpoint; 
$fields_string =  http_build_query($fields);  

curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string); 
curl_setopt($ch,CURLOPT_HTTPHEADER, array('X-method-override:UQUID', 
'Api-key:'.$config['Api-key'], 'Api-secret:'.$config['Api-secret']) );

 $server_output = curl_exec ($ch); 
 curl_close ($ch);   
 return $server_output;
}

function prettyPrint($json){   
$json = json_decode($json);    
echo '<pre>'.json_encode($json, JSON_PRETTY_PRINT).'</pre>'; }

请帮帮我。请告诉我。

1 个答案:

答案 0 :(得分:1)

我发现您正在使用REST服务,因此请尝试查看文章Calling a Web API From a .NET Client (C#)

不要忘记将Microsoft.AspNet.WebApi.Client引用添加到项目中。

要发送帖子请求,请执行以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;

namespace Api
{
    public class ApiCaller
    {
        public async Task<SomeReceivedEntity> CallApiAsync()
        {
            // prepare client
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://uquid.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Api-key", "YourApiKeyString");
                // your other headers ...

                // send request
                var data = new SomeSendedEntity() { ID = 10, Name = "Test" };
                HttpResponseMessage response = await client.PostAsJsonAsync("api", data);

                // verify results (throws exception on error response status code)
                response.EnsureSuccessStatusCode();

                // read, parse and return response
                return await response.Content.ReadAsAsync<SomeReceivedEntity>();
            }
        }
    }

    public class SomeSendedEntity
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }

    public class SomeReceivedEntity
    {
        public int ID { get; set; }
        public string Place { get; set; }
    }
}

未经测试,但您可以在文章中找到所需的一切。