How can i post data that required some parameter using rest api

first i am sorry because my english is bad :(
Hi! i have 3 data. first is id_krs which is string, detail_jawaban which is string[] and id_pertanyaan which is string[] too. i want to post data like this:
{
id_krs = "124234",
detail_jawaban = "sangat setuju",
id_pertanyaan = "517"
}
i want to post it using rest api. my api is like this : api.xxxx.ac.id/dev/api/evaluasi
there is no parameter in url. so i was confused how can i post parameters using that api?
is it using retrofit or httpclient or something like that?
thanks before :smile:

Best Answer

  • uday_Suddhalauday_Suddhala USMember ✭✭
    Accepted Answer

    either you can post request by using httpclient also :smile:

    var payload = new Credentials {
    Agent = new Agent {
    Name = "Agent Name",
    Version = 1
    },
    Username = "Username",
    Password = "User Password",
    Token = "xxxxx"
    };

    // Serialize our concrete class into a JSON String
    var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));

    // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
    var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

    using (var httpClient = new HttpClient()) {

    // Do the actual request and await the response
    var httpResponse = await httpClient.PostAsync("http://localhost/api/path", httpContent);
    
    // If the response contains content we want to read it!
    if (httpResponse.Content != null) {
        var responseContent = await httpResponse.Content.ReadAsStringAsync();
    
        // From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
    }
    

    }

    @mariayangotwskripsi

Answers

  • uday_Suddhalauday_Suddhala USMember ✭✭

    1.install newtonsoft.json from nuget for solution first

    2.then create a class file with name Restservice.cs,

    paste this in your class file:

    public string PostRequest(string url, string data)
    {

            try
            {
                responseString = null;
                // Create a new HttpWebRequest object.
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    
                request.ContentType = "application/x-www-form-urlencoded";
    
    
    
                // Set the Method property to 'POST' to post data to the URI.
                request.Method = "POST";
    
                inputDataString = data;
                // start the asynchronous operation 
                request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
    
                // Keep the main thread from continuing while the asynchronous
                // operation completes. A real world application
                // could do something useful such as updating its user interface. 
                allDone.WaitOne(100000); 
                allDone.Reset();
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
            return responseString;
        }
    

    3.now create a static class for performing API(service) calls eg: ClentCalls.cs

    4.now create a object for ur Restservice class

    private static RestService restService = new RestService();

    in this write a method:
    public static string SendData(string ID,string detailjawaban,string idpertanyan)
    {
    string Response = "";
    try
    {
    JObject jb = new JObject();
    jb.Add("id_krs ",ID);
    jb.Add("detail_jawaban", detailjawaban);
    jb.Add("id_pertanyaan ",idpertanyan);

                Response = restService.PostRequest("api.xxxx.ac.id/dev/api/evaluasi",+jb,"");
                return Response;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
    

    4.now from ur page call this method:

    var obj=clientcalls.SendData();

    you will get response here.

  • but detail_jawaban and id_pertanyaan has type data array string. is it fine to change
    public static string SendData(string ID,string detailjawaban,string idpertanyan)

    to
    public static string SendData(string ID,string[] detailjawaban,string[] idpertanyan) ?
    @uday_Suddhala

  • uday_Suddhalauday_Suddhala USMember ✭✭

    if that is a string array,you have to serialize the string array and then add to the object @mariayangotwskripsi

  • serialize object using newtonsoft.? can you give me example serialize string array?
    @uday_Suddhala

  • uday_Suddhalauday_Suddhala USMember ✭✭

    Product product = new Product();
    product.Name = "Apple";
    product.Expiry = new DateTime(2008, 12, 28);
    product.Price = 3.99M;
    product.Sizes = new string[] { "Small", "Medium", "Large" };

    string json = JsonConvert.SerializeObject(product);

    jb.Add("detail_jawaban", json);

    @mariayangotwskripsi

  • what is inputDataString,GetRequestStreamCallback and allDone in your code? it is not function, isn't it? @uday_Suddhala

  • uday_Suddhalauday_Suddhala USMember ✭✭
    Accepted Answer

    either you can post request by using httpclient also :smile:

    var payload = new Credentials {
    Agent = new Agent {
    Name = "Agent Name",
    Version = 1
    },
    Username = "Username",
    Password = "User Password",
    Token = "xxxxx"
    };

    // Serialize our concrete class into a JSON String
    var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));

    // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
    var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

    using (var httpClient = new HttpClient()) {

    // Do the actual request and await the response
    var httpResponse = await httpClient.PostAsync("http://localhost/api/path", httpContent);
    
    // If the response contains content we want to read it!
    if (httpResponse.Content != null) {
        var responseContent = await httpResponse.Content.ReadAsStringAsync();
    
        // From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
    }
    

    }

    @mariayangotwskripsi

  • what is the sign if http response is succesfully? i want to make sure if success then i make a Toast. @uday_Suddhala
    :smile:

  • uday_Suddhalauday_Suddhala USMember ✭✭

    @mariayangotwskripsi , sorry for late, here is the method you asked before for the first process:

    private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
    try
    {
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

                // End the operation
                Stream postStream = request.EndGetRequestStream(asynchronousResult);
    
                // Convert the string into a byte array.
                byte[] byteArray = Encoding.UTF8.GetBytes(inputDataString);
    
                // Write to the request stream.
                postStream.Write(byteArray, 0, inputDataString.Length);
                postStream.Dispose();
    
                // Start the asynchronous operation to get the response
                request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
            }
            catch
            { return; }
        }
    

    and this one is string u should declare.

    private static string inputDataString;

  • thanks @uday_Suddhala ! i will try it all. i can not try it now because to access that api need connection "intranet" in my campus

  • uday_Suddhalauday_Suddhala USMember ✭✭

    then follow this procedure:

    1.write a interface IRequestProvider:

    public interface IRequestProvider
    {
    Task GetAsync(string uri);

        Task<TResult> PostAsync<TResult>(string uri, TResult data);
    
        Task<TResult> PostAsync<TRequest, TResult>(string uri, TRequest data);
    
        Task<TResult> PutAsync<TResult>(string uri, TResult data);
    
        Task<TResult> PutAsync<TRequest, TResult>(string uri, TRequest data);
    }
    

    2.create a class RequestProvider

    public class RequestProvider : IRequestProvider
    {
    private readonly JsonSerializerSettings _serializerSettings;

        public RequestProvider()
        {
            _serializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                DateTimeZoneHandling = DateTimeZoneHandling.Local,
                NullValueHandling = NullValueHandling.Ignore                
            };
    
            _serializerSettings.Converters.Add(new StringEnumConverter());
        }
    
        public async Task<TResult> GetAsync<TResult>(string uri)
        {
            HttpClient httpClient = CreateHttpClient();
            HttpResponseMessage response = await httpClient.GetAsync(uri);
    
            await HandleResponse(response);
    
            string serialized = await response.Content.ReadAsStringAsync();
            TResult result = await Task.Run(() => JsonConvert.DeserializeObject<TResult>(serialized, _serializerSettings));
    
            return result;
        }
    
        public Task<TResult> PostAsync<TResult>(string uri, TResult data)
        {
            return PostAsync<TResult, TResult>(uri, data);
        }
    
        //Original
        //public async Task<TResult> PostAsync<TRequest, TResult>(string uri, TRequest data)
        //{
        //    HttpClient httpClient = CreateHttpClient();
        //    string serialized = await Task.Run(() => JsonConvert.SerializeObject(data, _serializerSettings));
        //    HttpResponseMessage response = await httpClient.PostAsync(uri, new StringContent(serialized, Encoding.UTF8, "application/json"));
    
        //    await HandleResponse(response);
    
        //    string responseData = await response.Content.ReadAsStringAsync();
    
        //    return await Task.Run(() => JsonConvert.DeserializeObject<TResult>(responseData, _serializerSettings));
        //}
    
        public async Task<TResult> PostAsync<TRequest, TResult>(string url, TRequest data)
        {
            try
            {
                UriBuilder builder = new UriBuilder(url);
                string uri = builder.ToString();
                HttpClient httpClient = CreateHttpClient();
                string serialized = await Task.Run(() => JsonConvert.SerializeObject(data, _serializerSettings));
    
                var content = new FormUrlEncodedContent(new[]
               {
                new System.Collections.Generic.KeyValuePair<string, string>("data",serialized)
               });
                HttpResponseMessage response = await httpClient.PostAsync(uri, content);
                if (response.IsSuccessStatusCode)
                {
                    await HandleResponse(response);
    
                    string responseData = await response.Content.ReadAsStringAsync();
                    JObject jobj = JObject.Parse(responseData);
                    return await Task.Run(() => JsonConvert.DeserializeObject<TResult>(jobj.ToString(), _serializerSettings));
                }
                else
                {
                    throw new  WebException();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Something went wrong at server ");
            }
        }
    
    
    
        public Task<TResult> PutAsync<TResult>(string uri, TResult data)
        {
            return PutAsync<TResult, TResult>(uri, data);
        }
    
        public async Task<TResult> PutAsync<TRequest, TResult>(string uri, TRequest data)
        {
            HttpClient httpClient = CreateHttpClient();
            string serialized = await Task.Run(() => JsonConvert.SerializeObject(data, _serializerSettings));
            HttpResponseMessage response = await httpClient.PutAsync(uri, new StringContent(serialized, Encoding.UTF8, "application/json"));
            await HandleResponse(response);
    
            string responseData = await response.Content.ReadAsStringAsync();
    
            return await Task.Run(() => JsonConvert.DeserializeObject<TResult>(responseData, _serializerSettings));
        }
    
        private HttpClient CreateHttpClient()
        {
            var httpClient = new HttpClient();
            httpClient.Timeout = new TimeSpan(0, 1, 0);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
            return httpClient;
        }
    
        private async Task HandleResponse(HttpResponseMessage response)
        {
            if (!response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
    
                if (response.StatusCode == HttpStatusCode.Forbidden || response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    throw new ServiceAuthenticationException(content);
                }
    
                throw new HttpRequestException(content);
            }
        }
    }
    

    3.create another class for ServiceAuthenticationException which we used in 2nd step

    public class ServiceAuthenticationException : Exception
    {
    public string Content { get; }

        public ServiceAuthenticationException()
        {
        }
    
        public ServiceAuthenticationException(string content)
        {
            Content = content;
        }
    }
    

    4.now create a object for ur request provider and consume in ur page:

    RequestProvider requestproviderjb = new RequestProvider();

    JObject response3 = await requestproviderjb.PostAsync(api.xxxx.ac.id/dev/api/evaluasi"", JObject.Parse("yourserialisedobject");
    //check with jobject
    if (response3["status"].ToString() == "success")
    {
    //perform action
    }

  • hi @uday_Suddhala , i have been try your code. and the output is:
    {id_krs:1231213,detail_jawaban:[sangat setuju,setuju,setuju],id_pertanyaan:[516,517,518]}
    this is succesful!
    but the problem is, my output json must be like:
    [
    {id_krs:1231312,detail_jawaban:sangat setuju,id_pertanyaan=516},
    {id_krs:1231322,detail_jawaban: setuju,id_pertanyaan=517},
    {id_krs:1231452,detail_jawaban:sangat setuju,id_pertanyaan=518}
    ]
    how can i output json like that? (array form)

  • edited:
    my data is : 1 id_krs, 3 detail_jawaban, 3 id_pertanyaan
    how can i output my json to be like this:
    {id_krs:1234, detail_jawaban:setuju,id_pertanyaan:516},
    {id_krs:1234, detail_jawaban:sangat setuju, id_pertanyaan:517},
    {id_krs:1234, detail_jawaban:setuju, id_pertanyaan:518}
    @uday_Suddhala

  • thank you so much @uday_Suddhala you are the best! your code worked !!
    God Bless you :blush:

Sign In or Register to comment.