Practical No :1
Write a program to implement to create a simple web service that converts the temperature from
Fahrenheit to Celsius and vice versa.
1. Imports
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link].* → for handling input/output streams.
[Link] → represents an IP address + port.
[Link].* → classes for creating a simple HTTP server in Java.
2. Main Class and Server Setup
public class TemperatureServer {
public static void main(String[] args) throws Exception {
HttpServer server = [Link](new InetSocketAddress(8080), 0);
[Link]("/toCelsius", new ToCelsiusHandler());
[Link]("/toFahrenheit", new ToFahrenheitHandler());
[Link](null);
[Link]("Server started on [Link]
[Link]();
}
}
[Link](new InetSocketAddress(8080), 0)
→ Creates a server that listens on port 8080.
→ The 0 means the server will use a default backlog for incoming connections.
createContext("/toCelsius", new ToCelsiusHandler())
→ Registers a URL path /toCelsius and associates it with a handler class that processes
requests.
[Link](null)
→ Uses the default executor (single-threaded by default).
[Link]()
→ Starts the server and begins listening for requests.
3. Handler for Fahrenheit → Celsius
static class ToCelsiusHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String query = [Link]().getQuery();
if (query == null || ) {
String response = "Error: parameter 'f' is required.";
sendResponse(exchange, response, 400);
return;
}
double f = [Link]([Link]("=")[1]);
double c = (f - 32) * 5 / 9;
String response = f + "°F = " + [Link]("%.2f", c) + "°C";
sendResponse(exchange, response, 200);
}
}
[Link]().getQuery()
→ Gets the query string from the URL (e.g., ?f=100 → "f=100").
if (query == null || )
→ Checks if the f parameter exists; otherwise, returns an error with status 400.
[Link]([Link]("=")[1])
→ Extracts the Fahrenheit value from the query and converts it to double.
double c = (f - 32) * 5 / 9
→ Formula to convert Fahrenheit to Celsius.
sendResponse(exchange, response, 200)
→ Sends the calculated response with HTTP status 200 (OK).
4. Handler for Celsius → Fahrenheit
static class ToFahrenheitHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String query = [Link]().getQuery();
if (query == null || ) {
String response = "Error: parameter 'c' is required.";
sendResponse(exchange, response, 400);
return;
}
double c = [Link]([Link]("=")[1]);
double f = c * 9 / 5 + 32;
String response = c + "°C = " + [Link]("%.2f", f) + "°F";
sendResponse(exchange, response, 200);
}
}
Works similarly to the Celsius handler but converts Celsius → Fahrenheit.
Formula: F = C × 9/5 + 32.
5. Helper Method: sendResponse
private static void sendResponse(HttpExchange exchange, String response, int status) throws
IOException {
byte[] bytes = [Link]("UTF-8");
[Link](status, [Link]);
OutputStream os = [Link]();
[Link](bytes);
[Link]();
[Link]();
}
● Converts the response string into bytes.
● Sends the HTTP status code (e.g., 200 for OK, 400 for Bad Request).
● Writes the response to the client and closes the output stream.
6. Example Usage
1. Start the server:
java TemperatureServer
1. Open a browser or use curl:
● Convert Fahrenheit to Celsius:
[Link]
Response:
100.0°F = 37.78°C
Convert Celsius to Fahrenheit
[Link]
Response:
37.78°C = 100.00°F
Summary
● This program is a basic REST-like service using Java HttpServer.
● Two endpoints handle conversion in both directions.
● Query parameters (f or c) are required.
● The server responds with a human-readable message
Overall Code:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class TemperatureServer {
public static void main(String[] args) throws Exception {
HttpServer server = [Link](new InetSocketAddress(8080), 0);
[Link]("/toCelsius", new ToCelsiusHandler());
[Link]("/toFahrenheit", new ToFahrenheitHandler());
[Link](null);
[Link]("Server started on [Link]
[Link]();
}
static class ToCelsiusHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String query = [Link]().getQuery();
if (query == null || ) {
String response = "Error: parameter 'f' is required.";
sendResponse(exchange, response, 400);
return;
}
double f = [Link]([Link]("=")[1]);
double c = (f - 32) * 5 / 9;
String response = f + "°F = " + [Link]("%.2f", c) + "°C";
sendResponse(exchange, response, 200);
}
}
static class ToFahrenheitHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String query = [Link]().getQuery();
if (query == null || ) {
String response = "Error: parameter 'c' is required.";
sendResponse(exchange, response, 400);
return;
}
double c = [Link]([Link]("=")[1]);
double f = c * 9 / 5 + 32;
String response = c + "°C = " + [Link]("%.2f", f) + "°F";
sendResponse(exchange, response, 200);
}
}
// ---- Helper method that ALWAYS sends a proper response ----
private static void sendResponse(HttpExchange exchange, String response, int status) throws
IOException {
byte[] bytes = [Link]("UTF-8");
[Link](status, [Link]);
OutputStream os = [Link]();
[Link](bytes);
[Link]();
[Link]();
}
}
OUTPUT:
Practical No 9
Use WCF to create a basic [Link] Asynchronous JavaScript and XML (AJAX) service
step by step to create a basic WCF service that can be consumed by AJAX in an [Link]
application. We'll use the asynchronous pattern so that the AJAX call does not block the UI.
Here’s a complete walkthrough:
Step 1: Create a WCF Service Library
1. Open Visual Studio → File → New → Project → WCF Service Library.
2. Name it, e.g., AjaxWcfService.
Step 2: Define the Service Contract
Open [Link] (or create a new one), and define an operation that returns a string. For AJAX,
use WebGet or WebInvoke attributes to enable HTTP GET/POST:
using [Link];
using [Link];
using [Link];
[ServiceContract]
public interface IAjaxService
{
[OperationContract]
[WebGet(ResponseFormat = [Link], UriTemplate = "GetMessage?
name={name}")]
Task<string> GetMessageAsync(string name);
}
WebGet makes it accessible via HTTP GET.
[Link] ensures the response is JSON.
Task<string> makes it asynchronous.
Step 3: Implement the Service
Open [Link]:
using [Link];
public class AjaxService : IAjaxService
{
public async Task<string> GetMessageAsync(string name)
{
// Simulate async work
await [Link](500);
return $"Hello, {name}! This message is from WCF.";
}
}
Step 4: Configure WCF for Web HTTP
Open [Link] and add the endpoint configuration:
<[Link]>
<services>
<service name="[Link]">
<endpoint
address=""
binding="webHttpBinding"
contract="[Link]"
behaviorConfiguration="webBehavior" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</[Link]>
Step 5: Add Service File (.svc)
Create [Link]:
<%@ ServiceHost Language="C#" Debug="true" Service="[Link]" %>
Step 6: Call the WCF Service Using AJAX
In your [Link] page (e.g., [Link]):
<script src="[Link]
<script>
function callWcfService() {
var name = $("#txtName").val();
$.ajax({
url: "[Link]/GetMessage?name=" + encodeURIComponent(name),
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#lblResult").text(response.d || response);
},
error: function (xhr, status, error) {
alert("Error: " + error);
}
});
}
</script>
<input type="text" id="txtName" placeholder="Enter your name" />
<button onclick="callWcfService()">Call Service</button>
<div id="lblResult"></div>
response.d is used when [Link] wraps JSON.
This call is asynchronous, so the UI does not block.
OUTPUT: er opens the page [Link].
User types a name in the input box (e.g., Alice).
User clicks the Call Service button.
AJAX sends a GET request to: