2015-10-14 45 views
0

Iam新的Java,我想做一個服務器發送JSON響應到客戶端,我試過下面的代碼,它工作正常。但是當我嘗試解析json時,它給出了有關內容類型不匹配的問題, 如何配置它以發送json respose?請幫助我。如何使Java服務器發送ison響應

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

} 
+1

只需使用Spring或Jersey。您可以使用Spring Boot在幾行中編寫整個程序:https://twitter.com/rob_winch/status/364871658483351552 – chrylis

+0

另一種選擇是使用類似[DropWizard](http://www.dropwizard.io/)這對於開發一個RESTful Web服務來說是一個偉大的鍋爐板,但可能會比您想要的稍重。 – vpiTriumph

+0

謝謝你們..我已經想通了.. –

回答

0

您需要指定Content-Type作爲appication/json。

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\" } } ] }"; 
       httpExchange.getResponseHeaders().set("Content-Type", "appication/json"); 
       t.sendResponseHeaders(200, response.length()); 
       OutputStream os = t.getResponseBody(); 
       os.write(response.getBytes()); 
       os.close(); 
      } 
     } 
+0

這對我很有幫助。我錯過了這個聲明。謝謝。 –

相關問題