0

i has a example code in php for getting result from curl but when i try call the function on c# i never get the result like php did

this is a code in php

$url = "http://localhost/ws/init.php";
$ch=curl_init();

curl_setopt($ch, CURLOPT_POST ,1);

$header=array();
$header[]='Content-Type: application/json';
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);


$data = json_encode($data);

curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$result=curl_exec($ch);
curl_close($ch);
return $result;

this is the result from php

{"error_code":"0","error_desc":"","data":{"token":"xyx"}}

i try using libcurl.net,HttpClient,WebRequest, and WebClient for getting the result like php code did but till now i still out of luck maybe someone can help me for solved this problem?

i appreciated with ur help guys

thanks you before

Rohit Poudel
  • 1,793
  • 2
  • 20
  • 24
KuroHito
  • 3
  • 3
  • Possible duplicate of [Making a cURL call in C#](https://stackoverflow.com/questions/7929013/making-a-curl-call-in-c-sharp) – chrisis Aug 11 '17 at 11:02

2 Answers2

0

You can use HttpClient for this operation. You can use something like that

public async Task<JsonObject> GetAsync(string uri)
    {
        var httpClient = new HttpClient();
        var content = await httpClient.GetStringAsync(uri);
        return await Task.Run(() => JsonObject.Parse(content));
    }
sonertbnc
  • 1,580
  • 16
  • 26
  • thank you for reply..the problem is i need to post json data to url and get the result.. i try this code but seems stuck at HttpResponseMessage HttpClient client = new HttpClient(); HttpResponseMessage response = await client.PostAsJsonAsync(url, json); ; string responseBody = await response.Content.ReadAsStringAsync(); return responseBody; – KuroHito Aug 12 '17 at 02:33
0

You can use RestSharp

example:

var client = new RestClient("http://localhost/ws/init.php");
var request = new RestRequest("", Method.POST);
var yourobject = new RequestObject(){....};
var json = request.JsonSerializer.Serialize(yourobject);    
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);

var myResponseData = client.Execute<MyResponseObject>(request);

response objects

public class DataObject
{
    public string token { get; set; }
}

public class MyResponseObject
{
    public string error_code { get; set; }
    public string error_desc { get; set; }
    public DataObject data { get; set; }
}
shay
  • 2,021
  • 1
  • 15
  • 17