Iam new to java, and I want to make a server which sends json response to client, I tried following code, It works fine . But When I try to parse json it gives problem regarding mismatch of content type, How do I configure it to send json respose? Please help me out.
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Test {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/SearchResult", new MyHandler());
server.setExecutor(null);
server.start();
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "{ \"contacts\": [ { \"id\": \"c200\", \"name\": \"Ravi Tamada\", \"email\": \"[email protected]\", \"address\": \"xx-xx-xxxx,x - street, x - country\", \"gender\" : \"male\", \"phone\": { \"mobile\": \"+91 0000000000\", \"home\": \"00 000000\", \"office\": \"00 000000\" } }, { \"id\": \"c201\", \"name\": \"Johnny Depp\", \"email\": \"[email protected]\", \"address\": \"xx-xx-xxxx,x - street, x - country\", \"gender\" : \"male\", \"phone\": { \"mobile\": \"+91 0000000000\", \"home\": \"00 000000\", \"office\": \"00 000000\" } } ] }";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
You need to specify Content-Type as appication/json.
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "...JSON...";
httpExchange.getResponseHeaders().set("Content-Type", "application/json");
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With