@@ -30,11 +30,17 @@ public static void main(String[] args) throws Exception {
3030 System .exit (1 );
3131 }
3232 byte [] body = getBodyContent (args [2 ]);
33- request =
34- HttpRequest .newBuilder ()
35- .uri (new URI (args [1 ]))
36- .POST (HttpRequest .BodyPublishers .ofByteArray (body ))
37- .build ();
33+ HttpRequest .Builder builder =
34+ HttpRequest .newBuilder ()
35+ .uri (new URI (args [1 ]))
36+ .POST (HttpRequest .BodyPublishers .ofByteArray (body ));
37+
38+ // For explicit inline strings (not @file), auto-detect JSON
39+ if (!args [2 ].startsWith ("@" ) && isJson (args [2 ])) {
40+ builder .header ("Content-Type" , "application/json" );
41+ }
42+
43+ request = builder .build ();
3844 } else if ("DELETE" .equals (method )) {
3945 request = HttpRequest .newBuilder ().uri (new URI (args [1 ])).DELETE ().build ();
4046 } else {
@@ -59,6 +65,24 @@ public static void main(String[] args) throws Exception {
5965 }
6066 }
6167
68+ /**
69+ * Checks if a string is valid JSON by attempting to parse it with Gson.
70+ *
71+ * @param text the string to check
72+ * @return true if the string is valid JSON
73+ */
74+ private static boolean isJson (String text ) {
75+ if (text == null || text .trim ().isEmpty ()) {
76+ return false ;
77+ }
78+ try {
79+ JsonParser .parseString (text );
80+ return true ;
81+ } catch (JsonSyntaxException e ) {
82+ return false ;
83+ }
84+ }
85+
6286 /**
6387 * Gets body content from either a file (prefixed with @) or inline string
6488 *
@@ -157,8 +181,8 @@ private static String filterJsonElement(JsonElement root, String fieldList) {
157181 for (String field : fields ) {
158182 String [] parts = field .trim ().split ("\\ ." );
159183 pathMap
160- .computeIfAbsent (parts [0 ], k -> new ArrayList <>())
161- .add (parts .length > 1 ? Arrays .copyOfRange (parts , 1 , parts .length ) : new String [0 ]);
184+ .computeIfAbsent (parts [0 ], k -> new ArrayList <>())
185+ .add (parts .length > 1 ? Arrays .copyOfRange (parts , 1 , parts .length ) : new String [0 ]);
162186 }
163187
164188 if (root .isJsonObject ()) {
@@ -213,16 +237,16 @@ private static JsonObject pickFields(JsonObject obj, List<String[]> subpaths) {
213237 } else {
214238 if (subValue .isJsonObject ()) {
215239 result .add (
216- fieldName ,
217- pickFields (
218- subValue .getAsJsonObject (),
219- Collections .singletonList (Arrays .copyOfRange (parts , 1 , parts .length ))));
240+ fieldName ,
241+ pickFields (
242+ subValue .getAsJsonObject (),
243+ Collections .singletonList (Arrays .copyOfRange (parts , 1 , parts .length ))));
220244 } else if (subValue .isJsonArray ()) {
221245 result .add (
222- fieldName ,
223- filterArray (
224- subValue .getAsJsonArray (),
225- Collections .singletonList (Arrays .copyOfRange (parts , 1 , parts .length ))));
246+ fieldName ,
247+ filterArray (
248+ subValue .getAsJsonArray (),
249+ Collections .singletonList (Arrays .copyOfRange (parts , 1 , parts .length ))));
226250 }
227251 }
228252 }
0 commit comments