C# httpClient does not return content
Use:
var responseString = await response.Content.ReadAsStringAsync();
The result will then be in responseString
.
Also one more problem:
You set your BaseAddress
as the CloudApi
, so now the requestUri
when you call PostAsync
should be blank. Like so:
var response = await client.PostAsync(String.Empty, content);
Also do yourself a favor and use the using
keyword provided by C#.
So here's what your full method should look like:
using(var client = new HttpClient())
{
client.BaseAddress = "http://baseApiAddress.com";
var values = new Dictionary<string, string>
{
{ "clientId", "cloudidx" },
{ "password", "65912" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("apiMethod", content);
string responseString = String.Empty;
if(response.IsSuccessStatusCode)
{
responseString = await response.Content.ReadAsStringAsync();
}
}
return View();
George Schneider
Updated on June 04, 2022Comments
-
George Schneider almost 2 years
public const string CloudApi = "https://www.idxhome.com/restServices/cloud-idx/login"; public const string password = "cloudidx"; public const string clientId = "65912"; public async Task<ActionResult> Index() { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(CloudApi); client.DefaultRequestHeaders.Accept.Clear(); var values = new Dictionary<string, string> { { "clientId", "cloudidx" }, { "password", "65912" } }; var content = new FormUrlEncodedContent(values); HttpResponseMessage response = await client.PostAsync(CloudApi,content); if (response.IsSuccessStatusCode) { var responseString = response.Content.ReadAsStringAsync().Result; response.Content.ToString(); } client.Dispose(); return View(); }
I have tried using HttpWebRequest as well as httpClient. I have looked through a dozen or so question on here and none of them have helped the situation.
I can use PHP and Curl and get the result I am looking for. The data returned in PHP is a JSON list of links. That looks like this..
"links":[ { "rel":"search", "href":"http://www.idxhome.com/restServices/cloud-idx/client/2/listing-search/MTM4NDMwMDg2MTA3ODoxYjExMWVhNDVlYWVmMjdiOTZhNTE5NjBhMjU3YzYzMzNhZmI0MzkwODk2MmExY2U0NU0ZjFiOGE3YzFhMTU4MjYxNjNlZjNhYjF-hZWFmNDI2ZWE3NmQwMjE4ODdjNmMzNGQxZmIxYTE4MGQ2MjUyM2YZWNhYjAwM2Q5MWFmNzgyYzM3NzcwYzFmNDk5OGM1Y2ExNDZhYjQwMDk2OWI4NmFhYTllZj..." }, { "rel":"detail", "href":"http://www.idxhome.com/restServices/cloud-idx/client/2/listing-search/MTM4NDMwMDg2MTA3ODoxYjExMWVhNDVlYWVmMjdiOTZhNTE5NjBhMjU3YzYzMzNhZmI0MzkwODk2MmExY2U0NU0ZjFiOGE3YzFhMTU4MjYxNjNlZjNhYjF-hZWFmNDI2ZWE3NmQwMjE4ODdjNmMzNGQxZmIxYTE4MGQ2MjUyM2YZWNhYjAwM2Q5MWFmNzgyYzM3NzcwYzFmNDk5OGM1Y2ExNDZhYjQwMDk2OWI4NmFhYTllZj..." }, { "rel":"cities", "href":"http://www.idxhome.com/restServices/cloud-idx/client/2/listing-search/MTM4NDMwMDg2MTA3ODoxYjExMWVhNDVlYWVmMjdiOTZhNTE5NjBhMjU3YzYzMzNhZmI0MzkwODk2MmExY2U0NU0ZjFiOGE3YzFhMTU4MjYxNjNlZjNhYjF-hZWFmNDI2ZWE3NmQwMjE4ODdjNmMzNGQxZmIxYTE4MGQ2MjUyM2YZWNhYjAwM2Q5MWFmNzgyYzM3NzcwYzFmNDk5OGM1Y2ExNDZhYjQwMDk2OWI4NmFhYTllZj..." }, { "rel":"zips", "href":"http://www.idxhome.com/restServices/cloud-idx/client/2/listing-search/MTM4NDMwMDg2MTA3ODoxYjExMWVhNDVlYWVmMjdiOTZhNTE5NjBhMjU3YzYzMzNhZmI0MzkwODk2MmExY2U0NU0ZjFiOGE3YzFhMTU4MjYxNjNlZjNhYjF-hZWFmNDI2ZWE3NmQwMjE4ODdjNmMzNGQxZmIxYTE4MGQ2MjUyM2YZWNhYjAwM2Q5MWFmNzgyYzM3NzcwYzFmNDk5OGM1Y2ExNDZhYjQwMDk2OWI4NmFhYTllZj..." } ], "cloudIdxSearchProfile":{ "bedrooms":2, "cityId":"274,284", "fullBaths":1, "lotAcres":0, "maxListPrice":1000000, "minListPrice":0, "newConstructionYn":false, "openHomesOnlyYn":false, "propertyType":"SFR,CND", "squareFeet":0, "zip":"94702,94703" }, "cloudIdxDetailProfile":{ "listingNumber":"88873733", "boardId":6 }, "message":"Include 'idxCloudSearchProfile' url parameters with requests to the 'search' URL. For 'detail' requests, include 'idxCloudDetailProfile' url parameters."`
API I am trying to utilize. It logs in with success but i cannot get the data that the call to login is suppose to pass along.
I believe there is a difference in the curl call and the httpclient call but i am not sure.
any help is appreciated. I have edited the code to the following but response string is still empty Copy of debug view
public async Task<ActionResult> Index() { using (var client = new HttpClient()) { client.BaseAddress = new Uri(CloudApi); client.DefaultRequestHeaders.Accept.Clear(); //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var values = new Dictionary<string, string> { { "clientId", "65912" }, { "password", "cloudidx" } }; var content = new FormUrlEncodedContent(values); HttpResponseMessage response = await client.PostAsync("login", content); string responseString = String.Empty; if (response.IsSuccessStatusCode) { responseString = await response.Content.ReadAsStringAsync(); } } return View(); }
here is the curl call that works
function cloudIDXCall($url, $method, $data = array()) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // return response as a string curl_setopt($curl, CURLOPT_SSLVERSION, 3); // force default SSL version to 3 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // turn off verification of the remote server's certificate - helps with Windows $queryString = http_build_query($data); // pack parameters into a URL query string if ($method == 'get') { // GET is the default request method for cURL if (strlen($queryString) > 0) $url = $url . '?' . $queryString; // append parameters for GET } elseif ($method == 'post') { curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $queryString); // set parameters for POST } else { return array('failure' => 'Invalid method'); } curl_setopt($curl, CURLOPT_URL, $url); $response = curl_exec($curl); if ( !$response ) { $errMsg = "Error: " . curl_error($curl) . " - Code: " . curl_errno($curl); curl_close($curl); return array('failure' => $errMsg); } $responseArray = json_decode ($response, $assoc = true); // decode JSON into assoc array curl_close($curl); return $responseArray;
}
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; solved the issue... Not sure why it made a difference but it did.
-
Yuriy Tseretyan about 7 yearsDid you try to add
await
toReadAsStringAsync
? -
John Wu about 7 yearsI do not see any code that displays the results or puts them in a variable to which your View will have access (e.g. ViewBag). Are you sure the data aren't actually being returned and you're simply failing to display it properly?
-
Crowcoder about 7 yearsDon't ever use .Result in asp.net. Google Stephen Cleary and find out why.
-
George Schneider about 7 years@JohnWu In debugging There was no content rendered. the header basically states that no content was returned
-
Alex about 7 yearsIt's because you are passing the endpoint and setting the BaseUri. So you probably aren't hitting the right endpoint and then also the .Result shouldn't be used. Just
await
the response ReadAsStringAsync. -
John Wu about 7 years@George-- exactly, you have witnessed an empty page. Might be an issue with rendering, not with data retrieval. Can you post the code from your view? Also, maybe set a break point and inspect the variables to see where the data are being lost along the way.
-
George Schneider about 7 years@johnWu it is not being delivered to the view. The responseString is where it should be. when i debug and look through the headers the content say that it is 0. It works in PHP using curl but not in C#.
-
Alex about 7 yearsAre you passing the parameters in the QueryString of the post or are you using the POST body?
-
-
George Schneider about 7 yearsTried this to no avail... the responseString is still empty.
-
George Schneider about 7 yearsits giving me status 200 OK
-
George Schneider about 7 yearsalso its in the query string... I am not sure how to put them in the post body?
-
George Schneider about 7 years
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
this solved my problem! I have no idea why but now i get the same data as I did with my curl call. -
George Schneider about 7 yearsI marked you as the answer because your suggestion to look at the difference between querystring and post body had led me to the header inspection and realization that there were issues in the security protocol
-
Alex about 7 yearsWell thanks! Wow okay so it was the security protocol! That's weird because I have never had to set that. Maybe if you would of just specified an https endpoint that might of happened but not sure.
-
George Schneider about 7 yearsYeah it has me thrown for a loop considering it was returning a 200 OK to me that means nothing was wrong with the call and it was returning what it should have been. Just one of those weird issues that sneak up.