java-okhttp.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. export const JavaOkhttpCodegen = {
  2. id: "java-okhttp",
  3. name: "Java OkHttp",
  4. language: "java",
  5. generator: ({
  6. auth,
  7. httpUser,
  8. httpPassword,
  9. method,
  10. url,
  11. pathName,
  12. queryString,
  13. bearerToken,
  14. headers,
  15. rawInput,
  16. rawParams,
  17. rawRequestBody,
  18. contentType,
  19. }) => {
  20. const requestString = []
  21. requestString.push(
  22. "OkHttpClient client = new OkHttpClient().newBuilder().build();"
  23. )
  24. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  25. let requestBody = rawInput ? rawParams : rawRequestBody
  26. if (contentType && contentType.includes("x-www-form-urlencoded")) {
  27. requestBody = `"${requestBody}"`
  28. } else {
  29. requestBody = requestBody ? JSON.stringify(requestBody) : null
  30. }
  31. if (contentType) {
  32. requestString.push(
  33. `MediaType mediaType = MediaType.parse("${contentType}");`
  34. )
  35. }
  36. if (requestBody) {
  37. requestString.push(
  38. `RequestBody body = RequestBody.create(mediaType,${requestBody});`
  39. )
  40. } else {
  41. requestString.push(
  42. "RequestBody body = RequestBody.create(null, new byte[0]);"
  43. )
  44. }
  45. }
  46. requestString.push("Request request = new Request.Builder()")
  47. requestString.push(`.url("${url}${pathName}?${queryString}")`)
  48. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  49. requestString.push(`.method("${method}", body)`)
  50. } else {
  51. requestString.push(`.method("${method}", null)`)
  52. }
  53. if (auth === "Basic Auth") {
  54. const basic = `${httpUser}:${httpPassword}`
  55. requestString.push(
  56. `.addHeader("authorization", "Basic ${window.btoa(
  57. unescape(encodeURIComponent(basic))
  58. )}") \n`
  59. )
  60. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  61. requestString.push(
  62. `.addHeader("authorization", "Bearer ${bearerToken}" ) \n`
  63. )
  64. }
  65. if (headers) {
  66. headers.forEach(({ key, value }) => {
  67. if (key) requestString.push(`.addHeader("${key}", "${value}")`)
  68. })
  69. }
  70. requestString.push(`.build();`)
  71. requestString.push("Response response = client.newCall(request).execute();")
  72. return requestString.join("\n")
  73. },
  74. }