java-okhttp.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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.includes("x-www-form-urlencoded")) {
  27. requestBody = `"${requestBody}"`
  28. } else requestBody = JSON.stringify(requestBody)
  29. requestString.push(
  30. `MediaType mediaType = MediaType.parse("${contentType}");`
  31. )
  32. requestString.push(
  33. `RequestBody body = RequestBody.create(mediaType,${requestBody});`
  34. )
  35. }
  36. requestString.push("Request request = new Request.Builder()")
  37. requestString.push(`.url("${url}${pathName}?${queryString}")`)
  38. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  39. requestString.push(`.method("${method}", body)`)
  40. } else {
  41. requestString.push(`.method("${method}", null)`)
  42. }
  43. if (auth === "Basic Auth") {
  44. const basic = `${httpUser}:${httpPassword}`
  45. requestString.push(
  46. `.addHeader("authorization", "Basic ${window.btoa(
  47. unescape(encodeURIComponent(basic))
  48. )}") \n`
  49. )
  50. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  51. requestString.push(
  52. `.addHeader("authorization", "Bearer ${bearerToken}" ) \n`
  53. )
  54. }
  55. if (headers) {
  56. headers.forEach(({ key, value }) => {
  57. if (key) requestString.push(`.addHeader("${key}", "${value}")`)
  58. })
  59. }
  60. requestString.push(`.build();`)
  61. requestString.push("Response response = client.newCall(request).execute();")
  62. return requestString.join("\n")
  63. },
  64. }