C# httpClient 不返回内容

Posted

技术标签:

【中文标题】C# httpClient 不返回内容【英文标题】:C# httpClient does not return content 【发布时间】:2017-02-20 23:25:35 【问题描述】:
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();

我尝试过使用 HttpWebRequest 和 httpClient。 我在这里查看了十几个问题,但没有一个对这种情况有所帮助。

我可以使用 php 和 Curl 来获得我想要的结果。 PHP 中返回的数据是一个 JSON 链接列表。好像是这样的。。

 "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。它成功登录,但我无法获取登录调用应该传递的数据。

我相信 curl 调用和 httpclient 调用有所不同,但我不确定。

感谢任何帮助。 我已将代码编辑为以下但响应字符串仍然为空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();
    

这是有效的 curl 调用

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.

【问题讨论】:

您是否尝试将await 添加到ReadAsStringAsync 我没有看到任何代码显示结果或将它们放入您的视图可以访问的变量中(例如 ViewBag)。您确定数据实际上并没有被返回,只是无法正确显示吗? 永远不要在 asp.net 中使用 .Result。谷歌 Stephen Cleary 并找出原因。 @JohnWu 在调试中没有渲染内容。标头基本上说明没有返回任何内容 这是因为您正在传递端点并设置 BaseUri。因此,您可能没有达到正确的端点,因此也不应该使用 .Result 。只需await 响应 ReadAsStringAsync。 【参考方案1】:

用途:

var responseString = await response.Content.ReadAsStringAsync();

然后结果将在responseString

还有一个问题:

您将BaseAddress 设置为CloudApi,所以现在当您调用PostAsyncrequestUri 应该为空。像这样:

var response = await client.PostAsync(String.Empty, content);

也帮自己一个忙,使用 C# 提供的 using 关键字。

所以你的完整方法应该是这样的:

    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();

【讨论】:

试过这个没用……responseString还是空的。 它给了我状态 200 OK 也在查询字符串中...我不知道如何将它们放在帖子正文中? System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; 这解决了我的问题!我不知道为什么,但现在我得到了与 curl 调用相同的数据。 我将您标记为答案,因为您建议查看查询字符串和帖子正文之间的差异,这使我进行了标头检查并意识到安全协议中存在问题

以上是关于C# httpClient 不返回内容的主要内容,如果未能解决你的问题,请参考以下文章

网络爬虫Java实现抓取网页内容

httpclient简介说明

C# HTTPClient 不发送请求

httpClient 配置与测试

带有标题和内容c#的HttpClient PostAsync [重复]

C# HttpClient 不发送 POST 变量