简体   繁体   English

HttpClient 后调用

[英]HttpClient Post Call

i want to do a REST POST call, using HttpClient.I keep having error - 'RestCall.PostRestCall(string, string, string, string)': not all code paths return a value'我想使用 HttpClient 进行 REST POST 调用。我一直有错误 - 'RestCall.PostRestCall(string, string, string, string)':并非所有代码路径都返回一个值'

Below is my Code.下面是我的代码。 Its meant to receive baseUrl, contentType, requestBody, httpMethod;它的意思是接收 baseUrl、contentType、requestBody、httpMethod; as input parameter and return the response status code, status description and response content.作为输入参数并返回响应状态码、状态描述和响应内容。

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

namespace RestPostCall
{
    public class RestCall
    {
        public static string PostRestCall(string baseURL, string httpMethod, string contentType, string requestBody)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(baseURL);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(new 
            MediaTypeWithQualityHeaderValue(contentType));

            // List data response.
            HttpResponseMessage response = client.GetAsync(requestBody).Result;
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body.
                var dataObjects = response.Content.ReadAsAsync<IEnumerable<IDataObject>>().Result;  
                //Make sure to add a reference to System.Net.Http.Formatting.dll

            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

            //Make any other calls using HttpClient here.

            //Dispose once all HttpClient calls are complete.
            client.Dispose();

         }
     }
 }

You method does not return any value, so change signature to return void type:您的方法不返回任何值,因此更改签名以返回void类型:

public static void PostRestCall(string baseURL, string httpMethod, string contentType, 
string requestBody)

将您的方法返回类型更改为 void,或者如果您想返回任何值,请使用 return 语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM