Search code examples
javac#asp.netcalling-convention

Calling addition function to calculate sum of input parameters


I have this set of codes (ASP.NET Web application) which calls an addition function of a java web service.

RestfulClient.cs

public class RestfulClient
{
    private static HttpClient client;

    internal Task addition(object firstNumber, object secondNumber)
    {
        throw new NotImplementedException();
    }

    private static string BASE_URL = "http://localhost:8080/";

    static RestfulClient()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri(BASE_URL);
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<string> addition(int firstNumber, int secondNumber)
    {
        try
        {
            var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
            var response = await client.GetAsync(endpoint);
            return await response.Content.ReadAsStringAsync();
        }
        catch (Exception e)
        {
            HttpContext.Current.Server.Transfer("ErrorPage.html");
        }
        return null;
    }
}

What codes should i add in my controller to call the addition function? I want user to input two numbers in the URL (When i run my ASP.NET Web API) and i want the ASP.NET Web API to be able to use the addition method which i have called from the java web service to calculate the sum and display it as e.g. {"firstNumber":9,"secondNumber":6,"sum":15}.

AdditionController.cs

public class AdditionController : ApiController
{
    private RestfulClient restfulClient = new RestfulClient();

    public IHttpActionResult Get(int firstNumber, int secondNumber)
    {
        //What do i have to include here?
        //Tried
        var result = restfulClient.addition(firstNumber, secondNumber); 
        return Json(result);

    }
}

I tried some codes however i do not get any output. The page just keeps loading without giving me any outputs.

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
        name: "AdditionApi",
        routeTemplate: "api/addition/{firstNumber}/{secondNumber}",
        defaults: new { action = "Get", controller = "Addition" }
        );
    }
}

Addition.java

public class Addition {

private int firstNumber, secondNumber, sum;

public Addition(String firstNumber, String secondNumber) {
    this.firstNumber = Integer.parseInt(firstNumber.trim());
    this.secondNumber = Integer.parseInt(secondNumber.trim());
    updateSum();
  }

public int getFirstNumber() {
    return firstNumber;
  }

public void setFirstNumber(int firstNumber) {
    this.firstNumber = firstNumber;
    updateSum();
  }

public int getSecondNumber() {
    return secondNumber;
  }

public void setSecondNumber(int secondNumber) {
    this.secondNumber = secondNumber;
    updateSum();
  }

public int getSum() {
    return sum;
  }

public void updateSum() {
    this.sum = this.firstNumber + this.secondNumber;
  }

@Override
public String toString() {
    return String.format("Addition [firstNumber=%d, secondNumber=%d, sum=%d%n", //
            firstNumber, secondNumber, sum);
  }
}

AdditionController.java

@RestController
public class AdditionController {

private static final String template = " %s";
private static int getSum;

@RequestMapping("/addition/{param1}/{param2}")
@ResponseBody 

public Addition addition 
            (@PathVariable("param1") int firstNumber,@PathVariable("param2") int secondNumber) {
return new Addition(
        (String.format(template, firstNumber)), String.format(template, secondNumber));
  }
}  

Someone please help me. Thank you so much in advance.


Solution

  • The problem turns out to be that in the RestfulClient.adition the program get's stuck on the line: var response = await client.GetAsync(endpoint); never receives a response. For now a fix could be:

    public string addition(int firstNumber, int secondNumber)
            {
                try
                {
                    var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
                    HttpResponseMessage response = client.GetAsync(endpoint).Result;
                    //This will check whether or not the response was executed successfully(status code 200ish or not 
                    if (response.IsSuccessStatusCode)
                    {
                        return response.Content.ReadAsStringAsync().Result;
                    }
                    else
                    {
                        throw new Exception($"The server responded with a bad request of type: {response.StatusCode}");
                    }
                }
                catch (Exception e)
                {
                    HttpContext.Current.Server.Transfer("ErrorPage.html");
                }
                return null;
            }
    

    In case someone got a less work around ish solution to this problem please share.