Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Java server to send ison response

Tags:

java

json

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();
        }
    }

}
like image 544
Raaz Dhakal Avatar asked Oct 14 '15 01:10

Raaz Dhakal


1 Answers

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();
            }
        }
like image 178
Nazarii Moshenskiy Avatar answered Sep 28 '22 17:09

Nazarii Moshenskiy