{"id":15494880,"url":"https://github.com/fracpete/requests4j","last_synced_at":"2025-04-22T20:25:38.915Z","repository":{"id":39925316,"uuid":"207969308","full_name":"fracpete/requests4j","owner":"fracpete","description":"HTTP for humans, inspired by the amazing Python requests library.","archived":false,"fork":false,"pushed_at":"2024-08-14T02:29:06.000Z","size":154,"stargazers_count":7,"open_issues_count":0,"forks_count":4,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-19T12:15:44.165Z","etag":null,"topics":["http","httpclient","java"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fracpete.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-09-12T05:09:12.000Z","updated_at":"2024-08-14T02:29:09.000Z","dependencies_parsed_at":"2023-12-11T21:24:09.044Z","dependency_job_id":"e998c783-3c06-4412-8cf5-0d887805eb24","html_url":"https://github.com/fracpete/requests4j","commit_stats":null,"previous_names":[],"tags_count":22,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fracpete%2Frequests4j","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fracpete%2Frequests4j/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fracpete%2Frequests4j/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fracpete%2Frequests4j/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fracpete","download_url":"https://codeload.github.com/fracpete/requests4j/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250317310,"owners_count":21410720,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["http","httpclient","java"],"created_at":"2024-10-02T08:15:29.831Z","updated_at":"2025-04-22T20:25:38.899Z","avatar_url":"https://github.com/fracpete.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# requests4j\n*HTTP for humans* using Java, inspired by the amazing [requests Python library](https://2.python-requests.org/en/master/).\nNot as feature rich, but it gets a lot done.\n\n## Why yet another Java HTTP client library? \n[JSoup](https://jsoup.org/) was missing some functionality that I needed and \nthe [Apache HttpClient](http://hc.apache.org/httpcomponents-client-ga/)\nlibrary seemed a bit too cumbersome to use. Initially, I reused functionality\nthat I had written for my [ADAMS](https://adams.cms.waikato.ac.nz/) framework\nover the years and turned it into a separate library, taking\nthe [requests](https://2.python-requests.org/en/master/) API as model to make\nthis library easy to use. \n\n## API Changes\n* Version 0.1.0 swapped out the underlying code, now using \n  [Apache's HttpClient](http://hc.apache.org/httpcomponents-client-ga/) for doing \n  the actual work.\n* Version 0.2.0 replaced [Apache's HttpClient](http://hc.apache.org/httpcomponents-client-ga/)\n  with [Square's OkHttp](https://square.github.io/okhttp/). This was unfortunately\n  necessary as Android ships with an outdated version of Apache's HttpClient, \n  resulting in method signature errors.\n\n\n## Usage\nThe following sections describe how to use the library.\n\n### Creating a request\nThe following methods are supported through the `com.github.fracpete.requests4j.Requests` class:\n* GET -- `Requests.get()`\n* POST -- `Requests.post()`\n* PUT -- `Requests.put()`\n* PATCH -- `Requests.patch()`\n* HEAD -- `Requests.head()`\n* OPTIONS -- `Requests.options()`\n* DELETE -- `Requests.delete()`\n\nThe above mentioned methods can also take a URL string or a `java.net.URL` object,\ninitializing the URL straight away. Otherwise, you need to set the URL via \nthe `url(String)` or `url(java.net.URL)` method. \n\nCalling one the request methods will generate an instance of the `Request` \nclass (package `com.github.fracpete.requests4j.request`). This class supports\ndaisy-chaining to make it easy to configure a full request with minimal code \nto write.\n\n\n### Headers and parameters\nYou can set custom HTTP headers using the following methods:\n* `header(String,String)` -- setting a single header, name and value\n* `headers(Map\u003cString,String\u003e)` -- setting multiple headers at once\n\nSimilarly, you can set parameters, eg to be encoded in the URL for `GET` \nrequests, using the following methods:\n* `parameter(String,String)` -- setting a single parameter, name and value.\n* `parameter(String,String[])` or `parameter(String,List)` -- setting \n  multiple string values for the parameter.\n* `parameters(Map\u003cString,Object\u003e)` -- setting multiple parameters at once, \n  ensures that the values of the map only contain `String`, `String[]` \n  or `java.util.List`.\n\n\n### HTML forms\nBeing able to upload data, be it simple parameters or files, is an important\nfeature for a HTTP client library. In case of `GET`, you can only use simple\nparameters, as they get appended to the URL of the request. `POST`, on the\nother hand, makes use of the `multipart/form-data` content type, allowing\nyou to upload files (or any binary data) as well.\n\nIn order to make use of form data, you need to call the `formData(FormData)`\nmethod, with an instance of `FormData` (package `com.github.fracpete.requests4j.form`).\nThe `FormData` class allows you to either add parameter objects (derived from `AbstractParameter`)\nor directly add simple parameters, files or input streams (eg a `java.io.ByteArrayInputStream` \nif you have the data only in its binary form).\n\nThe following example POSTs a file to the server with some credentials as part\nof the form data: \n\n```java\nimport com.github.fracpete.requests4j.Requests;\nimport com.github.fracpete.requests4j.response.BasicResponse;\nimport com.github.fracpete.requests4j.form.FormData;\n\npublic class FormUpload {\n  public static void main(String[] args) throws Exception {\n    BasicResponse r = Requests.post(\"http://some.server.com/upload\")\n      .formData(\n        new FormData()\n          .addFile(\"file\", \"/some/where/important.doc\")\n          .add(\"user\", \"myuser\")\n          .add(\"password\", \"mysecretpassword\")\n      )\n      .execute();\n    System.out.printnl(r);\n  }\n}\n```\n\n### Posting data\nYou can easily *post* a single file or data (i.e., byte array) using the `attachment(AbstractAttachment)`\nmethod. Available attachment types (package `com.github.fracpete.requests4j.attachment`) are:\n* `ByteArrayAttachment`  \n* `FileAttachment`\n\nSuch an attachment will add a `Content-Disposition` header to the request:\n* `ByteArrayAttachment`: `attachment`\n* `FileAttachment`: `attachment; name=\"file\"; filename=\"NAME\"`\n\nThe following example posts the file supplied as command-line argument:\n\n```java\nimport com.github.fracpete.requests4j.Requests;\nimport com.github.fracpete.requests4j.response.BasicResponse;\nimport com.github.fracpete.requests4j.attachment.FileAttachment;\nimport java.io.File;\n\npublic class PostData {\n  public static void main(String[] args) throws Exception {\n    File f = new File(args[0]);\n    BasicResponse r = Requests.post(\"http://some.server.com/\")\n      .attachment(new FileAttachment(f))\n      .execute();\n    System.out.printnl(r);\n  }\n}\n```\n\n### Execute and response\nOnce fully configured, you can execute a request with the `execute()` method,\nwhich will either fail with an exception or return a `BasicResponse` object (package \n`com.github.fracpete.requests4j.response`).\n\nWith a `BasicResponse` object, you have access to:\n* HTTP status code -- `statusCode()`\n* HTTP status message -- `statusMessage()`\n* HTTP headers -- `headers()`\n* raw HTTPClient response -- `rawResponse()`\n* the body of the response\n  * the raw byte array -- `body()`\n  * as (UTF-8) text -- `text()`\n  * as text using a custom encoding -- `text(String)`\n\nWith the `saveBody` methods, you can save the binary response data as is to the \nsupplied file.\n\n\n### Json\nYou can also send and receive Json quite easily. For that purpose, requests4j \noffers the `Dictionary` and `Array` classes (package: `com.github.fracpete.requests4j.json`)\nto allow method chaining and easily construct request. These two classes have\nstatic methods, to shorten the instantiation:\n\n```java\nimport com.github.fracpete.requests4j.Requests;\nimport com.github.fracpete.requests4j.response.JsonResponse;\nimport static com.github.fracpete.requests4j.json.Array.newArray;\nimport static com.github.fracpete.requests4j.json.Dictionary.newDict;\n\npublic class JsonPost {\n  public static void main(String[] args) throws Exception {\n    String url = \"https://some.host.com/api/\";\n    JsonResponse r = Requests.post(url)\n\t  .body(newDict()\n\t    .add(\"a\", 1.234)\n\t    .add(\"b\", true)\n\t    .add(\"c\", newDict()\n\t\t.add(\"z\", 1.2f))\n\t    .add(\"d\", newArray()\n\t\t.add(1, 2, 3, 4)))\n\t.execute(new JsonResponse());\n    System.out.println(r.json());\n  }\n}\n```\n\n\n## Sessions\nTo avoid having to string along and update any cookies for requests, you can\nsimply create a `Session` object which will take of that (package `com.github.fracpete.requests4j`).\nThe `Session` object has the same methods for instantiating request (though this \ntime non-static) as the `Requests` class described above. The `Session` class\nalso supports hostname verification (see below), which it will apply to each\nsubsequent request. \n\n```java\nimport com.github.fracpete.requests4j.Requests;\nimport com.github.fracpete.requests4j.Session;\nimport com.github.fracpete.requests4j.response.BasicResponse;\n\npublic class SessionExample {\n  public static void main(String[] args) {\n    Session session = new Session();\n    BasicResponse login = session.post(\"http://some.server.com/login\")\n      .formData(\n        new FormData()\n          .add(\"user\", \"myuser\")\n          .add(\"password\", \"mysecretpassword\")\n      )\n      .execute();\n    if (login.ok()) {\n      BasicResponse action = session.get(\"http://some.server.com/somethingelse\")\n        .execute();\n      System.out.println(action.text());\n    }\n  }\n}\n```\n\n\n## Advanced usage\n### Different response objects\nThe `BasicResponse` object simply stores the received data in memory, which is fine\nfor receiving HTML pages or small binary objects. However, for downloading\nlarge binary files, it is recommended to use one of the following response\nclasses instead (package `com.github.fracpete.requests4j.response`):\n* `FileResponse` - streams the incoming data straight to the specified output file\n* `StreamResponse` - uses the supplied `java.io.OutputStream` to forward the incoming data to  \n\nEach of these classes implements the `Response` interface that all response\nclasses share, giving you access to the following methods:\n* HTTP status code -- `statusCode()`\n* HTTP status message -- `statusMessage()`\n* HTTP headers -- `headers()`\n* raw HTTPClient response -- `rawResponse()`\n\nInstead of using the `execute()` method, you now use the `execute(Response)` \nmethod, supplying the fully configured response object. The following example\nshows how to download a remote ZIP file straight to a file:\n```java\nimport com.github.fracpete.requests4j.Requests;\nimport com.github.fracpete.requests4j.response.FileResponse;\n\npublic class FileResponseDownload {\n  public static void main(String[] args) {\n    FileResponse r = Requests.get(\"http://some.server.com/largefile.zip\")\n      .execute(new FileResponse(\"/some/where/largefile.zip\"));\n    if (r.ok())\n      System.out.println(\"Saved to \" + r.outputFile());\n  }\n}\n```\n\n### Authentication\nSome websites may require you to log in via password dialogs (eg Apache's htpasswd functionality).\nIn that case, you can use `BasicAuthentication` to provide these credentials:\n\n```java\nimport com.github.fracpete.requests4j.Requests;\nimport com.github.fracpete.requests4j.auth.BasicAuthentication;\nimport com.github.fracpete.requests4j.response.BasicResponse;\n\npublic class Auth {\n  public static void main(String[] args) throws Exception {\n    BasicResponse r = Requests.get(\"http://some.server.com/\")\n      .auth(new BasicAuthentication(\"USER\", \"PASSWORD\"))\n      .execute();\n  }\n}\n```\n\n### Redirects\nSome websites, like sourceforge may perform redirects (eg from `http` to `https`).\nBy default redirects are not allowed, but you can enable them using the \n`allowRedirects(boolean)` method. With the `maxRedirects(int)` method you can \nset the upper limit to the number of redirects to follow through (default is 3).\n\nThe following example downloads a Weka zip file from sourceforge.net:\n\n```java\npublic class Redirect {\n  public static void main(String[] args) throws Exception {\n    BasicResponse r = Requests.get(\"http://sourceforge.net/projects/weka/files/weka-3-9/3.9.3/weka-3-9-3.zip/download\")\n      .allowRedirects(true)\n      .execute();\n  }\n}\n```\n\n\n### Proxies\nBasic proxy support is available through the `proxy(...)` and `noProxy()`\nmethods. The following request configures a proxy (`proxy.domain.com:80`) for \nhttp connections:\n\n```java\npublic class Redirect {\n  public static void main(String[] args) throws Exception {\n    BasicResponse r = Requests.get(\"http://some.server.com/\")\n      .proxy(\"proxy.domain.com\", 80, \"http\")\n      .execute();\n  }\n}\n```\n\n\n### URLs\nThe `URLBuilder` class (package `com.github.fracpete.requests4j.request`) is\nused by the `Request` class internally to construct the URL for `GET` requests.\nHowever, it can be used as standalone class as well to construct URLs, arguments \nonly or with protocol/port/file. It allows you to append simply key-value pairs, \nkeys with multiple values (String array or collection) and maps. The following code:\n\n```java\nimport com.github.fracpete.requests4j.request.URLBuilder;\npublic class BuildURL {\n  public static void main(String[] args) throws Exception {\n    Map pairs = new HashMap();\n    pairs.put(\"m\", \"m1\");\n    URL url = new URL(\"http\", \"somehost.com\", \"/api\");\n    URLBuilder builder = new URLBuilder(url)\n      .append(\"a\", \"a1\")\n      .append(\"b\", new String[]{\"b1\", \"b2\", \"b3\"})\n      .append(\"c\", Arrays.asList(\"c1\", \"c2\"))\n      .append(pairs);\n    System.out.println(builder.build());\n  }\n}\n```\n\nWill generate the following output:\n\n```\nhttp://somehost.com/api?a=a1\u0026b=b1\u0026b=b2\u0026b=b3\u0026c=c1\u0026c=c2\u0026m=m1\n```\n\n\n## Examples\n\n* [ReadHtml](src/main/java/com/github/fracpete/requests4j/examples/ReadHtml.java) -- grabs the start\n  page of *github.com* (storing the response in memory), dumps it to standard out, next to the cookies it received. \n* [DownloadWeka](src/main/java/com/github/fracpete/requests4j/examples/DownloadWeka.java) -- downloads \n  a Weka zip file and streams the downloaded file straight to disk\n* [DownloadWekaAsStream](src/main/java/com/github/fracpete/requests4j/examples/DownloadWekaAsStream.java) -- downloads \n  a Weka zip file to a supplied output stream.\n* [WebHook](src/main/java/com/github/fracpete/requests4j/examples/Webhook.java) -- sends a POST request\n  to [https://webhook.site] and outputs the response. You need to supply the API key as first argument\n  (which you get by visiting the site).\n* [WebHookForm](/com/github/fracpete/requests4j/examples/WebhookForm.java) -- sends URL-encoded form data \n  to [https://webhook.site] and outputs the response. You need to supply the API key as first argument\n  (which you get by visiting the site).\n \n\n## Maven\nUse the following dependency in your `pom.xml`:\n```xml\n    \u003cdependency\u003e\n      \u003cgroupId\u003ecom.github.fracpete\u003c/groupId\u003e\n      \u003cartifactId\u003erequests4j\u003c/artifactId\u003e\n      \u003cversion\u003e0.2.6\u003c/version\u003e\n    \u003c/dependency\u003e\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffracpete%2Frequests4j","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffracpete%2Frequests4j","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffracpete%2Frequests4j/lists"}