Reputation: 109
I have an ASP.NET Web API which is supposed to call a java addition web service. When i run the java web service and type url http://localhost:8080/addition/9/6
i get {"firstNumber":9,"secondNumber":6,"sum":15}
as the output data. Right now, i want to use the ASP.NET Web API to call and display that data when i run the ASP.NET Web API application. How do i go about doing that?
Here are my codes:
ASP.NET Web API Codes
RestfulClient.cs
public class RestfulClient
{
private string BASE_URL = "http://localhost:8080/addition/";
public Task<string> addition()
{
{
try
{
var client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("addition").Result;
return response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
HttpContext.Current.Server.Transfer("ErrorPage.html");
}
return null;
}
}
}
ApiController.cs
private RestfulClient restfulClient = new RestfulClient();
public ActionResult Index()
{
var Result1 = restfulClient.addition().Result;
return Content(Result1);
}
Java Web Service Codes
AdditionController.java
@RestController
public class AdditionController {
private static final String template = " %s";
private static int getSum;
@RequestMapping("/addition/{param1}/{param2}")
@ResponseBody
public Addition getSum
(@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.
Upvotes: 2
Views: 2392
Reputation: 246998
According to the Java service, the URL you are calling from the client is not formatted correctly based on your base URL and the one used in the GetAsync
.
public class RestfulClient {
private static HttpClient client;
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 a, int b) {
try {
var endpoint = string.Format("addition/{0}/{1}", a, b);
var response = await client.GetAsync(endpoint);
return await response.Content.ReadAsStringAsync();
} catch (Exception e) {
HttpContext.Current.Server.Transfer("ErrorPage.html");
}
return null;
}
}
The controller would also need to be updated.
public async Task<ActionResult> Index() {
int a = 9;
int b = 6;
var result = await restfulClient.addition(a, b);
return Content(result);
}
Note the proper use of the HttpClient
as suggested in the comments and as well as the use of async/await.
Upvotes: 1