How to escape special character Restful API query string in JAVA

Viewed 969

I try to modify existing query string to filter specified condition: now query string is below:

String bodycontent="{"
                +"  \"_source\": [\"@timestamp\",\"eqpid\",\"lotid\",\"stageid\",\"srvmethod\",\"parm_1\",\"apcack\",\"description\",\"host\",\"path\",\"action\"],"
                +"  \"query\": {"
                +"    \"query_string\" : {"
                +"        \"query\":\" lotid:"+q_lotid+" AND "+host_type+"\"}"
                +"  },"
                +"  \"sort\" : [{\"@timestamp\" : { \"order\" : \"desc\" }}]"
                +"}";

I want to change the query condition below:

query :
type:ams_log AND (alm_source:K*) AND (alm_id:TCS00004 OR alm_id:TCS00005 OR alm_id:TCS00007 OR alm_id:TCS00008 OR alm_id:TCS00009 OR alm_id:TCS00010 OR alm_id:TCS00011 OR alm_id:TCS00012 OR alm_id:TCS00013 OR alm_id:TCS00020 OR alm_id:TCS00024 OR alm_id:TCS00032)

but I am confused how to modify the query string with slash \ and Double quotes ". I can't find the rule, thanks!

1 Answers
  • Slash - \\
  • Quote - \"

System.out.println("\\ \"hello\"");

Output:

\ "hello"


Regarding your query, seems like both key and value must be in between quotes "key":"value"

String lotId="2020_A_88";
String type="apples";
String queryPart = "\"lotId\":\""+lotId+"\" AND \"type\":\""+type+"\"";
System.out.println(queryPart);    

"lotId":"2020_A_88" AND "type":"apples"


String example = String.format("Slash-> %s , Quotes-> %s", "\\" ,"\"name\""); 
System.out.println(example);

Slash-> \ , Quotes-> "name"


String s = "\\";
String q = "\"name\"";
System.out.println("Slash-> "+s+" , Quotes-> "+q);

Slash-> \ , Quotes-> "name"

Related