2011-12-16 31 views
0

我想要做一些SQL查詢與我的Java的HttpServer但似乎HttpServer的不我提交到我的瀏覽器鏈接識別的特殊字符:如何讓HttpServer識別Java中的特殊字符?

[1]: http://localhost:8001/test?query=SELECT * WHERE{ ?s rdf:type ?o. } 

我總是收到這樣的響應:

400 Bad Request 
URISyntaxException thrown 

這是我的服務器代碼:

public class SimpleHttpServer 
{ 

public static void main(String[] args) throws Exception 
{ 

     dir = args[0]; 
     HttpServer server = HttpServer.create(new InetSocketAddress(8001), 0); 
     server.createContext("/test", new MyHandler()); 
     server.setExecutor(null); 
     server.start(); 
    } 

    static class MyHandler implements HttpHandler { 
     public void handle(HttpExchange t) throws IOException { 
      String response ; 
      System.out.println(t.getRequestURI().getQuery().toString().replaceAll("query=", "")); 
      response = ExecuteHttpQuery.getInstance().httpQuery(t.getRequestURI().getQuery().toString().replaceAll("query=", "").toString(), dir) + "\n"; 
      t.sendResponseHeaders(200, response.length()); 
      OutputStream os = t.getResponseBody(); 
      os.write(response.getBytes()); 
      os.close(); 
     } 
    } 
} 

我怎樣才能解決這個問題?

+2

你可能想要urlencode你的鏈接,因爲它包含空格和其他符號。請參閱http://en.wikipedia.org/wiki/Percent-encoding – clamp 2011-12-16 13:09:55

回答

4

你不應該在你的URL中傳遞你的SQL查詢。

+0

+1,不能過分強調這一點。 – Perception 2011-12-16 13:19:43

+0

可以閱讀http://en.wikipedia.org/wiki/SQL_injection以獲取原因。 – Vadzim 2011-12-16 13:58:13

5

是的,有某些字符在url的某些部分無效。 (除了我希望你只是測試這個,並沒有真正用於任何真正的SQL注入攻擊和所有的),你需要先使用URLEncoder對sql查詢進行編碼。