Skip to content

k.net.httpClient ​

Outbound HTTP: unified send, multiple request bodies, and batch tasks

Execution ContextPrerequisitesTypical Use
KScript API, Page / View server scriptsOutbound HTTP access; multipart file examples read from k.fileProxying third-party APIs, custom headers/bodies, and batch downloads

k.net.httpClient encapsulates outbound requests based on HttpClient, supporting JSON, forms, multipart uploads, and parallel batch downloads. Prefer this module when proxying third-party APIs. Single requests return KHttpResponse, exposing success, statusCode, bodyString(), and more.

Quick Start ​

js
k.api.post("proxy", () => {
  const content = k.net.httpClient.createJsonContent({ q: "hello" })
  const response = k.net.httpClient.send("https://httpbin.org/post", "post", content)
  return {
    ok: response.success,
    status: response.statusCode,
    body: response.bodyString()
  }
})

Quick Reference ​

Method / PropertyDescriptionReturns
createJsonContent(body)Create an application/json request bodyKHttpContent
createStringContent(body)Create a plain text request bodyKHttpContent
createFormUrlEncodedContent(body)Create an application/x-www-form-urlencoded bodyKHttpContent
createMultipartFormDataContent()Create a multipart body supporting fields and filesKMultipartHttpContent
createBatchRequest()Create a batch container and add tasks with addTask()KBatchRequest
send(url, method[, content[, headers[, timeout]]])Send a single HTTP requestKHttpResponse
send(request)Execute a batch request and populate RequestTask resultsvoid

Create request body ​

MethodParametersReturnDescription
createJsonContent(body)anyKHttpContentapplication/json
createStringContent(body)stringKHttpContentPlain text
createFormUrlEncodedContent(body)Record<string, any>KHttpContentapplication/x-www-form-urlencoded
createMultipartFormDataContent()NoneKMultipartHttpContentMultipart, supports add and addFile

All content objects (KHttpContent and KMultipartHttpContent) expose setHeader(name, value): void and getHeader(name): string[]; the 4th parameter contentType on addFile(name, fileName, binary, contentType?) is optional.

js
const json = k.net.httpClient.createJsonContent({ name: "kooboo" })
const text = k.net.httpClient.createStringContent("plain text")
const form = k.net.httpClient.createFormUrlEncodedContent({ key: "value" })

const multipart = k.net.httpClient.createMultipartFormDataContent()
multipart.add("name", "jobs")
multipart.addFile("sticker", "1.png", k.file.readBinary("1.png"), "image/png")
multipart.setHeader("X-Trace-Id", "trace-001")
const headerVals = multipart.getHeader("X-Trace-Id")

send() ​

Send a single HTTP request and return KHttpResponse.

ParameterTypeRequiredDescription
urlstringYesFull URL
methodstringYesget, post, put, delete, options (case-insensitive; any other value such as patch falls back to GET)
contentKHttpContentNoRequest body; usually omitted for GET
headersobjectNoAdditional request header key-value pairs
timeoutnumberNoTimeout in seconds

Returns: KHttpResponse.

js
k.api.post("proxy", () => {
  const content = k.net.httpClient.createJsonContent({ q: "hello" })
  const response = k.net.httpClient.send("https://httpbin.org/post", "post", content, {
    "X-Request-Source": "kooboo"
  }, 15)
  return {
    ok: response.success,
    status: response.statusCode,
    body: response.bodyString()
  }
})

KHttpResponse common members ​

MemberDescription
successHTTP success status code
statusCodeNumeric status code
bodyString()Response body text
bodyBinary()Response body byte array
getHeader(name)Read response headers (array of strings)
contentType{ mediaType, charSet }
contentDisposition{ fileName, size }
save(path) / saveBinary(path)Write response to a site k.file path and return FileInfo
js
const response = k.net.httpClient.send("https://example.com/file.zip", "get")
if (response.success) {
  response.save("downloads/archive.zip")
}

Bulk request ​

Create a batch container via createBatchRequest(), append tasks with addTask(url, method), set responseType, and pass the container to send(batch).

ParameterTypeRequiredDescription
requestKBatchRequestYesBatch request object returned by createBatchRequest()

Returns: void; results are populated on each batch.tasks[i].

RequestTask common fields:

FieldDescription
urlRequest URL
methodHTTP method
timeoutTimeout in seconds
contentRequest body (KHttpContent)
headerRequest headers map
responseType"String", "Binary", "File"
savePathRequired when responseType is "File", relative site file path
isSuccessWhether the task succeeded
statusCodeHTTP status code
errorMessageError message on failure
stringResult / binaryResult / fileResultStore results by type
js
const batch = k.net.httpClient.createBatchRequest()
const imgTask = batch.addTask("https://www.kooboo.com/img/logo-white.png", "get")
imgTask.responseType = "File"
imgTask.savePath = "logo-white.png"

const jsonTask = batch.addTask("https://httpbin.org/json", "get")
jsonTask.responseType = "String"

k.net.httpClient.send(batch)

return {
  imageOk: batch.tasks[0].isSuccess,
  jsonSnippet: batch.tasks[1].stringResult ? batch.tasks[1].stringResult.slice(0, 80) : ""
}

TypeScript Definitions ​

Show full TypeScript definitions
ts
interface KHttpClient {
  createJsonContent(body: any): KHttpContent;
  createStringContent(body: string): KHttpContent;
  createFormUrlEncodedContent(body: Record<string, any>): KHttpContent;
  createMultipartFormDataContent(): KMultipartHttpContent;
  createBatchRequest(): KBatchRequest;
  send(url: string, method: string, content?: KHttpContent, headers?: Record<string, any>, timeout?: number): KHttpResponse;
  send(request: KBatchRequest): void;
}

interface KHttpContent {
  getHeader(name: string): string[];
  setHeader(name: string, value: string): void;
}

interface KMultipartHttpContent extends KHttpContent {
  addFile(name: string, fileName: string, binary: number[], contentType?: string): void;
  add(name: string, value: string): void;
  getHeader(name: string): string[];
  setHeader(name: string, value: string): void;
}

interface KBatchRequest {
  tasks: RequestTask[];
  addTask(url: string, method: string): RequestTask;
}

interface KHttpResponse {
  contentDisposition?: KContentDisposition;
  contentType?: KContentType;
  success: boolean;
  statusCode: number;
  getHeader(name: string): string[];
  bodyString(): string;
  bodyBinary(): number[];
  save(path: string): FileInfo;
  saveBinary(path: string): FileInfo;
}

interface RequestTask {
  url: string;
  method: string;
  timeout: number;
  content: KHttpContent;
  header: Record<string, any>;
  responseType: ResponseType;
  savePath: string;
  isSuccess: boolean;
  statusCode: number;
  errorMessage: string;
  fileResult: FileInfo;
  stringResult: string;
  binaryResult: number[];
}

interface KContentDisposition {
  fileName?: string;
  size?: number;
}

interface KContentType {
  mediaType: string;
  charSet: string;
}

type ResponseType = 'String' | 'Binary' | 'File';