如何让HttpServer识别Java中的特殊字符?
问题描述:
我想要做一些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();
}
}
}
我怎样才能解决这个问题?
答
你不应该在你的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
答
是的,有某些字符在url的某些部分无效。 (除了我希望你只是测试这个,并没有真正用于任何真正的SQL注入攻击和所有的),你需要先使用URLEncoder对sql查询进行编码。
你可能想要urlencode你的链接,因为它包含空格和其他符号。请参阅http://en.wikipedia.org/wiki/Percent-encoding – clamp 2011-12-16 13:09:55