pax_global_header00006660000000000000000000000064126545161020014514gustar00rootroot0000000000000052 comment=6f3e56e8dae9479f5c8a9f121834ecc99ed5e76d unirest-java-unirest-java-1.4.8/000077500000000000000000000000001265451610200165445ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/.editorconfig000066400000000000000000000003711265451610200212220ustar00rootroot00000000000000# http://editorconfig.org root = true [*] indent_style = tab indent_size = 1 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.{xml,yml}] indent_size = 2 [*.{md,yml}] trim_trailing_whitespace = false unirest-java-unirest-java-1.4.8/.gitignore000066400000000000000000000001561265451610200205360ustar00rootroot00000000000000.classpath pom.xml.releaseBackup .project target .DS_Store .settings release.properties META-INF .idea *.iml unirest-java-unirest-java-1.4.8/.travis.yml000066400000000000000000000001341265451610200206530ustar00rootroot00000000000000language: java jdk: - openjdk6 - openjdk7 - oraclejdk7 - oraclejdk8 os: - linux unirest-java-unirest-java-1.4.8/LICENSE000066400000000000000000000021131265451610200175460ustar00rootroot00000000000000The MIT License Copyright (c) 2013-2015 Mashape (https://www.mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. unirest-java-unirest-java-1.4.8/README.md000066400000000000000000000310401265451610200200210ustar00rootroot00000000000000# Unirest for Java [![Build Status][travis-image]][travis-url] ![][unirest-logo] [Unirest](http://unirest.io) is a set of lightweight HTTP libraries available in multiple languages, built and maintained by [Mashape](https://github.com/Mashape), who also maintain the open-source API Gateway [Kong](https://github.com/Mashape/kong). Do yourself a favor, and start making HTTP requests like this: ```java Unirest.post("http://httpbin.org/post") .queryString("name", "Mark") .field("last", "Polo") .asJson() ``` [![License][license-image]][license-url] | [![version][maven-version]][maven-url] | [![Gitter][gitter-image]][gitter-url] ## Features * Make `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS` requests * Both syncronous and asynchronous (non-blocking) requests * It supports form parameters, file uploads and custom body entities * Easily add route parameters without ugly string concatenations * Supports gzip * Supports Basic Authentication natively * Customizable timeout, concurrency levels and proxy settings * Customizable default headers for every request (DRY) * Customizable `HttpClient` and `HttpAsyncClient` implementation * Automatic JSON parsing into a native object for JSON responses * Customizable binding, with mapping from response body to java Object ## Installing Is easy as pie. Kidding. It's about as easy as doing these little steps: ### With Maven You can use Maven by including the library: ```xml com.mashape.unirest unirest-java 1.4.8 ``` There are dependencies for Unirest-Java, these should be already installed, and they are as follows: ```xml org.apache.httpcomponents httpclient 4.3.6 org.apache.httpcomponents httpasyncclient 4.0.2 org.apache.httpcomponents httpmime 4.3.6 org.json json 20140107 ``` If you would like to run tests, also add the following dependency along with the others: ```xml junit junit 4.11 test commons-io commons-io 2.4 test ``` ### Without Maven Alternatively if you don't use Maven, you can directly include the JAR file in the classpath: http://oss.sonatype.org/content/repositories/releases/com/mashape/unirest/unirest-java/1.4.8/unirest-java-1.4.8.jar Don't forget to also install the dependencies ([`org.json`](http://www.json.org/java/), [`httpclient 4.3.6`](http://hc.apache.org/downloads.cgi), [`httpmime 4.3.6`](http://hc.apache.org/downloads.cgi), [`httpasyncclient 4.0.2`](http://hc.apache.org/downloads.cgi)) in the classpath too. There is also a way to generate a Unirest-Java JAR file that already includes the required dependencies, but you will need Maven to generate it. Follow the instructions at http://blog.mashape.com/post/69117323931/installing-unirest-java-with-the-maven-assembly-plugin ## Creating Request So you're probably wondering how using Unirest makes creating requests in Java easier, here is a basic POST request that will explain everything: ```java HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .queryString("apiKey", "123") .field("parameter", "value") .field("foo", "bar") .asJson(); ``` Requests are made when `as[Type]()` is invoked, possible types include `Json`, `Binary`, `String`, `Object`. If the request supports and it is of type `HttpRequestWithBody`, a body it can be passed along with `.body(String|JsonNode|Object)`. For using `.body(Object)` some pre-configuration is needed (see below). If you already have a map of parameters or do not wish to use seperate field methods for each one there is a `.fields(Map fields)` method that will serialize each key - value to form parameters on your request. `.headers(Map headers)` is also supported in replacement of multiple header methods. ## Serialization Before an `asObject(Class)` or a `.body(Object)` invokation, is necessary to provide a custom implementation of the `ObjectMapper` interface. This should be done only the first time, as the instance of the ObjectMapper will be shared globally. For example, serializing Json from\to Object using the popular Jackson ObjectMapper takes only few lines of code. ```java // Only one time Unirest.setObjectMapper(new ObjectMapper() { private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); public T readValue(String value, Class valueType) { try { return jacksonObjectMapper.readValue(value, valueType); } catch (IOException e) { throw new RuntimeException(e); } } public String writeValue(Object value) { try { return jacksonObjectMapper.writeValueAsString(value); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }); // Response to Object HttpResponse bookResponse = Unirest.get("http://httpbin.org/books/1").asObject(Book.class); Book bookObject = bookResponse.getBody(); HttpResponse authorResponse = Unirest.get("http://httpbin.org/books/{id}/author") .routeParam("id", bookObject.getId()) .asObject(Author.class); Author authorObject = authorResponse.getBody(); // Object to Json HttpResponse postResponse = Unirest.post("http://httpbin.org/authors/post") .header("accept", "application/json") .header("Content-Type", "application/json") .body(authorObject) .asJson(); ``` ### Route Parameters Sometimes you want to add dynamic parameters in the URL, you can easily do that by adding a placeholder in the URL, and then by setting the route parameters with the `routeParam` function, like: ```java Unirest.get("http://httpbin.org/{method}") .routeParam("method", "get") .queryString("name", "Mark") .asJson(); ``` In the example above the final URL will be `http://httpbin.org/get` - Basically the placeholder `{method}` will be replaced with `get`. The placeholder's format is as easy as: `{custom_name}` ## Asynchronous Requests Sometimes, well most of the time, you want your application to be asynchronous and not block, Unirest supports this in Java using anonymous callbacks, or direct method placement: ```java Future> future = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("param1", "value1") .field("param2", "value2") .asJsonAsync(new Callback() { public void failed(UnirestException e) { System.out.println("The request has failed"); } public void completed(HttpResponse response) { int code = response.getStatus(); Map headers = response.getHeaders(); JsonNode body = response.getBody(); InputStream rawBody = response.getRawBody(); } public void cancelled() { System.out.println("The request has been cancelled"); } }); ``` ## File Uploads Creating `multipart` requests with Java is trivial, simply pass along a `File` Object as a field: ```java HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("parameter", "value") .field("file", new File("/tmp/file")) .asJson(); ``` ## Custom Entity Body ```java HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .body("{\"parameter\":\"value\", \"foo\":\"bar\"}") .asJson(); ``` ## Byte Stream as Entity Body ```java final InputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); final byte[] bytes = new byte[stream.available()]; stream.read(bytes); stream.close(); final HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post") .field("name", "Mark") .field("file", bytes, "image.jpg") .asJson(); ``` ## InputStream as Entity Body ```java HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post") .field("name", "Mark") .field("file", new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())), ContentType.APPLICATION_OCTET_STREAM, "image.jpg") .asJson(); ``` ## Basic Authentication Authenticating the request with basic authentication can be done by calling the `basicAuth(username, password)` function: ```java HttpResponse response = Unirest.get("http://httpbin.org/headers").basicAuth("username", "password").asJson(); ``` # Request The Java Unirest library follows the builder style conventions. You start building your request by creating a `HttpRequest` object using one of the following: ```java GetRequest request = Unirest.get(String url); GetRequest request = Unirest.head(String url); HttpRequestWithBody request = Unirest.post(String url); HttpRequestWithBody request = Unirest.put(String url); HttpRequestWithBody request = Unirest.patch(String url); HttpRequestWithBody request = Unirest.options(String url); HttpRequestWithBody request = Unirest.delete(String url); ``` # Response Upon recieving a response Unirest returns the result in the form of an Object, this object should always have the same keys for each language regarding to the response details. - `.getStatus()` - HTTP Response Status Code (Example: 200) - `.getStatusText()` - HTTP Response Status Text (Example: "OK") - `.getHeaders()` - HTTP Response Headers - `.getBody()` - Parsed response body where applicable, for example JSON responses are parsed to Objects / Associative Arrays. - `.getRawBody()` - Un-parsed response body # Advanced Configuration You can set some advanced configuration to tune Unirest-Java: ### Custom HTTP clients You can explicitly set your own `HttpClient` and `HttpAsyncClient` implementations by using the following methods: ```java Unirest.setHttpClient(httpClient); Unirest.setAsyncHttpClient(asyncHttpClient); ``` ### Timeouts You can set custom connection and socket timeout values (in **milliseconds**): ```java Unirest.setTimeouts(long connectionTimeout, long socketTimeout); ``` By default the connection timeout (the time it takes to connect to a server) is `10000`, and the socket timeout (the time it takes to receive data) is `60000`. You can set any of these timeouts to zero to disable the timeout. ### Default Request Headers You can set default headers that will be sent on every request: ```java Unirest.setDefaultHeader("Header1", "Value1"); Unirest.setDefaultHeader("Header2", "Value2"); ``` You can clear the default headers anytime with: ```java Unirest.clearDefaultHeaders(); ``` ### Concurrency You can set custom concurrency levels if you need to tune the performance of the syncronous or asyncronous client: ```java Unirest.setConcurrency(int maxTotal, int maxPerRoute); ``` By default the maxTotal (overall connection limit in the pool) is `200`, and the maxPerRoute (connection limit per target host) is `20`. ### Proxy You can set a proxy by invoking: ```java Unirest.setProxy(new HttpHost("127.0.0.1", 8000)); ``` # Exiting an application Unirest starts a background event loop and your Java application won't be able to exit until you manually shutdown all the threads by invoking: ```java Unirest.shutdown(); ``` ---- Made with ♥ from the [Mashape](https://www.mashape.com/) team [unirest-logo]: http://cl.ly/image/2P373Y090s2O/Image%202015-10-12%20at%209.48.06%20PM.png [license-url]: https://github.com/Mashape/unirest-java/blob/master/LICENSE [license-image]: https://img.shields.io/badge/license-MIT-blue.svg?style=flat [gitter-url]: https://gitter.im/Mashape/unirest-java [gitter-image]: https://img.shields.io/badge/Gitter-Join%20Chat-blue.svg?style=flat [travis-url]: https://travis-ci.org/Mashape/unirest-java [travis-image]: https://img.shields.io/travis/Mashape/unirest-java.svg?style=flat [maven-url]: http://search.maven.org/#browse%7C1262490619 [maven-version]: https://img.shields.io/maven-central/v/com.mashape.unirest/unirest-java.svg?style=flat [versioneye-url]: https://www.versioneye.com/user/projects/54b83a12050646ca5c0001fc [versioneye-image]: https://www.versioneye.com/user/projects/54b83a12050646ca5c0001fc/badge.svg?style=flat unirest-java-unirest-java-1.4.8/deploy000077500000000000000000000006141265451610200177670ustar00rootroot00000000000000#!/bin/bash mvn clean deploy mvn release:clean git commit -a -m "version bump" git push origin master mvn release:prepare mvn release:perform # Note: Be sure that the local Maven settings.xml file is configured with the right credentials, and that the system has the right GPG keys installed (along with a valid GPG installation) # Now go to https://oss.sonatype.org/index.html and release it unirest-java-unirest-java-1.4.8/formatter/000077500000000000000000000000001265451610200205475ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/formatter/unirest-code-format.xml000066400000000000000000000750341265451610200251710ustar00rootroot00000000000000 unirest-java-unirest-java-1.4.8/pom.xml000066400000000000000000000075631265451610200200740ustar00rootroot00000000000000 4.0.0 com.mashape.unirest unirest-java jar 1.4.8 unirest-java Simplified, lightweight HTTP client library http://unirest.io/ org.sonatype.oss oss-parent 7 MIT http://opensource.org/licenses/MIT repo https://github.com/Mashape/unirest-java scm:git:git@github.com:Mashape/unirest-java.git scm:git:git@github.com:Mashape/unirest-java.git mashape Mashape opensource@mashape.com https://github.com/Mashape Mashape https://www.mashape.com UTF-8 UTF-8 2.6.0 org.apache.maven.plugins maven-compiler-plugin 3.1 true 128m 512m 1.5 1.5 UTF-8 org.apache.maven.plugins maven-assembly-plugin 2.4 jar-with-dependencies org.apache.maven.plugins maven-source-plugin 2.2.1 attach-sources jar org.apache.maven.plugins maven-javadoc-plugin 2.9.1 attach-javadocs jar org.apache.httpcomponents httpclient 4.3.6 org.apache.httpcomponents httpasyncclient 4.0.2 org.apache.httpcomponents httpmime 4.3.6 org.json json 20140107 junit junit 4.12 test commons-io commons-io 2.4 test com.fasterxml.jackson.core jackson-databind ${jackson.version} test unirest-java-unirest-java-1.4.8/src/000077500000000000000000000000001265451610200173335ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/000077500000000000000000000000001265451610200202575ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/000077500000000000000000000000001265451610200212005ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/000077500000000000000000000000001265451610200217565ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/000077500000000000000000000000001265451610200233745ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/000077500000000000000000000000001265451610200250655ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/000077500000000000000000000000001265451610200260445ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/Headers.java000066400000000000000000000005661265451610200302710ustar00rootroot00000000000000package com.mashape.unirest.http; import java.util.HashMap; import java.util.List; public class Headers extends HashMap> { private static final long serialVersionUID = 71310341388734766L; public String getFirst(Object key) { List list = get(key); if (list != null && list.size() > 0) { return list.get(0); } return null; } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/HttpClientHelper.java000066400000000000000000000205441265451610200321320ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import java.net.URL; import java.net.URLDecoder; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.http.HttpEntity; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.nio.entity.NByteArrayEntity; import com.mashape.unirest.http.async.Callback; import com.mashape.unirest.http.async.utils.AsyncIdleConnectionMonitorThread; import com.mashape.unirest.http.exceptions.UnirestException; import com.mashape.unirest.http.options.Option; import com.mashape.unirest.http.options.Options; import com.mashape.unirest.http.utils.ClientFactory; import com.mashape.unirest.request.HttpRequest; public class HttpClientHelper { private static final String CONTENT_TYPE = "content-type"; private static final String ACCEPT_ENCODING_HEADER = "accept-encoding"; private static final String USER_AGENT_HEADER = "user-agent"; private static final String USER_AGENT = "unirest-java/1.3.11"; private static FutureCallback prepareCallback(final Class responseClass, final Callback callback) { if (callback == null) return null; return new FutureCallback() { public void cancelled() { callback.cancelled(); } public void completed(org.apache.http.HttpResponse arg0) { callback.completed(new HttpResponse(arg0, responseClass)); } public void failed(Exception arg0) { callback.failed(new UnirestException(arg0)); } }; } public static Future> requestAsync(HttpRequest request, final Class responseClass, Callback callback) { HttpUriRequest requestObj = prepareRequest(request, true); CloseableHttpAsyncClient asyncHttpClient = ClientFactory.getAsyncHttpClient(); if (!asyncHttpClient.isRunning()) { asyncHttpClient.start(); AsyncIdleConnectionMonitorThread asyncIdleConnectionMonitorThread = (AsyncIdleConnectionMonitorThread) Options.getOption(Option.ASYNC_MONITOR); asyncIdleConnectionMonitorThread.start(); } final Future future = asyncHttpClient.execute(requestObj, prepareCallback(responseClass, callback)); return new Future>() { public boolean cancel(boolean mayInterruptIfRunning) { return future.cancel(mayInterruptIfRunning); } public boolean isCancelled() { return future.isCancelled(); } public boolean isDone() { return future.isDone(); } public HttpResponse get() throws InterruptedException, ExecutionException { org.apache.http.HttpResponse httpResponse = future.get(); return new HttpResponse(httpResponse, responseClass); } public HttpResponse get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { org.apache.http.HttpResponse httpResponse = future.get(timeout, unit); return new HttpResponse(httpResponse, responseClass); } }; } public static HttpResponse request(HttpRequest request, Class responseClass) throws UnirestException { HttpRequestBase requestObj = prepareRequest(request, false); HttpClient client = ClientFactory.getHttpClient(); // The // DefaultHttpClient // is thread-safe org.apache.http.HttpResponse response; try { response = client.execute(requestObj); HttpResponse httpResponse = new HttpResponse(response, responseClass); requestObj.releaseConnection(); return httpResponse; } catch (Exception e) { throw new UnirestException(e); } finally { requestObj.releaseConnection(); } } private static HttpRequestBase prepareRequest(HttpRequest request, boolean async) { Object defaultHeaders = Options.getOption(Option.DEFAULT_HEADERS); if (defaultHeaders != null) { @SuppressWarnings("unchecked") Set> entrySet = ((Map) defaultHeaders).entrySet(); for (Entry entry : entrySet) { request.header(entry.getKey(), entry.getValue()); } } if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) { request.header(USER_AGENT_HEADER, USER_AGENT); } if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) { request.header(ACCEPT_ENCODING_HEADER, "gzip"); } HttpRequestBase reqObj = null; String urlToRequest = null; try { URL url = new URL(request.getUrl()); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef()); urlToRequest = uri.toURL().toString(); if (url.getQuery() != null && !url.getQuery().trim().equals("")) { if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) { urlToRequest += "?"; } urlToRequest += url.getQuery(); } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) { urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1); } } catch (Exception e) { throw new RuntimeException(e); } switch (request.getHttpMethod()) { case GET: reqObj = new HttpGet(urlToRequest); break; case POST: reqObj = new HttpPost(urlToRequest); break; case PUT: reqObj = new HttpPut(urlToRequest); break; case DELETE: reqObj = new HttpDeleteWithBody(urlToRequest); break; case PATCH: reqObj = new HttpPatchWithBody(urlToRequest); break; case OPTIONS: reqObj = new HttpOptions(urlToRequest); break; case HEAD: reqObj = new HttpHead(urlToRequest); break; } Set>> entrySet = request.getHeaders().entrySet(); for (Entry> entry : entrySet) { List values = entry.getValue(); if (values != null) { for (String value : values) { reqObj.addHeader(entry.getKey(), value); } } } // Set body if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) { if (request.getBody() != null) { HttpEntity entity = request.getBody().getEntity(); if (async) { if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) { reqObj.setHeader(entity.getContentType()); } try { ByteArrayOutputStream output = new ByteArrayOutputStream(); entity.writeTo(output); NByteArrayEntity en = new NByteArrayEntity(output.toByteArray()); ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en); } catch (IOException e) { throw new RuntimeException(e); } } else { ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity); } } } return reqObj; } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/HttpDeleteWithBody.java000066400000000000000000000031111265451610200324170ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.http; import java.net.URI; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { public static final String METHOD_NAME = "DELETE"; public String getMethod() { return METHOD_NAME; } public HttpDeleteWithBody(final String uri) { super(); setURI(URI.create(uri)); } public HttpDeleteWithBody(final URI uri) { super(); setURI(uri); } public HttpDeleteWithBody() { super(); } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/HttpMethod.java000066400000000000000000000022661265451610200307750ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.http; public enum HttpMethod { GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS; } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/HttpPatchWithBody.java000066400000000000000000000031041265451610200322560ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.http; import java.net.URI; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; class HttpPatchWithBody extends HttpEntityEnclosingRequestBase { public static final String METHOD_NAME = "PATCH"; public String getMethod() { return METHOD_NAME; } public HttpPatchWithBody(final String uri) { super(); setURI(URI.create(uri)); } public HttpPatchWithBody(final URI uri) { super(); setURI(uri); } public HttpPatchWithBody() { super(); } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/HttpResponse.java000066400000000000000000000110231265451610200313420ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.http; import com.mashape.unirest.http.options.Option; import com.mashape.unirest.http.options.Options; import com.mashape.unirest.http.utils.ResponseUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.StatusLine; import org.apache.http.util.EntityUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; public class HttpResponse { private int statusCode; private String statusText; private Headers headers = new Headers(); private InputStream rawBody; private T body; @SuppressWarnings("unchecked") public HttpResponse(org.apache.http.HttpResponse response, Class responseClass) { HttpEntity responseEntity = response.getEntity(); ObjectMapper objectMapper = (ObjectMapper) Options.getOption(Option.OBJECT_MAPPER); Header[] allHeaders = response.getAllHeaders(); for (Header header : allHeaders) { String headerName = header.getName(); List list = headers.get(headerName); if (list == null) list = new ArrayList(); list.add(header.getValue()); headers.put(headerName, list); } StatusLine statusLine = response.getStatusLine(); this.statusCode = statusLine.getStatusCode(); this.statusText = statusLine.getReasonPhrase(); if (responseEntity != null) { String charset = "UTF-8"; Header contentType = responseEntity.getContentType(); if (contentType != null) { String responseCharset = ResponseUtils.getCharsetFromContentType(contentType.getValue()); if (responseCharset != null && !responseCharset.trim().equals("")) { charset = responseCharset; } } try { byte[] rawBody; try { InputStream responseInputStream = responseEntity.getContent(); if (ResponseUtils.isGzipped(responseEntity.getContentEncoding())) { responseInputStream = new GZIPInputStream(responseEntity.getContent()); } rawBody = ResponseUtils.getBytes(responseInputStream); } catch (IOException e2) { throw new RuntimeException(e2); } this.rawBody = new ByteArrayInputStream(rawBody); if (JsonNode.class.equals(responseClass)) { String jsonString = new String(rawBody, charset).trim(); this.body = (T) new JsonNode(jsonString); } else if (String.class.equals(responseClass)) { this.body = (T) new String(rawBody, charset); } else if (InputStream.class.equals(responseClass)) { this.body = (T) this.rawBody; } else if (objectMapper != null) { this.body = objectMapper.readValue(new String(rawBody, charset), responseClass); } else { throw new Exception("Only String, JsonNode and InputStream are supported, or an ObjectMapper implementation is required."); } } catch (Exception e) { throw new RuntimeException(e); } } try { EntityUtils.consume(responseEntity); } catch (IOException e) { throw new RuntimeException(e); } } public int getStatus() { return statusCode; } public String getStatusText() { return statusText; } /** * @return Response Headers (map) with same case as server response. * For instance use getHeaders().getFirst("Location") and not getHeaders().getFirst("location") to get first header "Location" */ public Headers getHeaders() { return headers; } public InputStream getRawBody() { return rawBody; } public T getBody() { return body; } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/JsonNode.java000066400000000000000000000042571265451610200304360ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.http; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class JsonNode { private JSONObject jsonObject; private JSONArray jsonArray; private boolean array; public JsonNode(String json) { if (json == null || "".equals(json.trim())) { jsonObject = new JSONObject(); } else { try { jsonObject = new JSONObject(json); } catch (JSONException e) { // It may be an array try { jsonArray = new JSONArray(json); array = true; } catch (JSONException e1) { throw new RuntimeException(e1); } } } } public JSONObject getObject() { return this.jsonObject; } public JSONArray getArray() { JSONArray result = this.jsonArray; if (array == false) { result = new JSONArray(); result.put(jsonObject); } return result; } public boolean isArray() { return this.array; } @Override public String toString() { if (isArray()) { if (jsonArray == null) return null; return jsonArray.toString(); } if (jsonObject == null) return null; return jsonObject.toString(); } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/ObjectMapper.java000066400000000000000000000002351265451610200312620ustar00rootroot00000000000000package com.mashape.unirest.http; public interface ObjectMapper { T readValue(String value, Class valueType); String writeValue(Object value); } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/Unirest.java000066400000000000000000000142661265451610200303510ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.http; import com.mashape.unirest.http.async.utils.AsyncIdleConnectionMonitorThread; import com.mashape.unirest.http.options.Option; import com.mashape.unirest.http.options.Options; import com.mashape.unirest.http.utils.SyncIdleConnectionMonitorThread; import com.mashape.unirest.request.GetRequest; import com.mashape.unirest.request.HttpRequestWithBody; import org.apache.http.HttpHost; import org.apache.http.client.HttpClient; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class Unirest { /** * Set the HttpClient implementation to use for every synchronous request */ public static void setHttpClient(HttpClient httpClient) { Options.setOption(Option.HTTPCLIENT, httpClient); Options.customClientSet(); } /** * Set the asynchronous AbstractHttpAsyncClient implementation to use for every asynchronous request */ public static void setAsyncHttpClient(CloseableHttpAsyncClient asyncHttpClient) { Options.setOption(Option.ASYNCHTTPCLIENT, asyncHttpClient); Options.customClientSet(); } /** * Set a proxy */ public static void setProxy(HttpHost proxy) { Options.setOption(Option.PROXY, proxy); // Reload the client implementations Options.refresh(); } /** * Set the ObjectMapper implementation to use for Response to Object binding * * @param objectMapper Custom implementation of ObjectMapper interface */ public static void setObjectMapper(ObjectMapper objectMapper) { Options.setOption(Option.OBJECT_MAPPER, objectMapper); // Reload the client implementations Options.refresh(); } /** * Set the connection timeout and socket timeout * * @param connectionTimeout The timeout until a connection with the server is established (in milliseconds). Default is 10000. Set to zero to disable the timeout. * @param socketTimeout The timeout to receive data (in milliseconds). Default is 60000. Set to zero to disable the timeout. */ public static void setTimeouts(long connectionTimeout, long socketTimeout) { Options.setOption(Option.CONNECTION_TIMEOUT, connectionTimeout); Options.setOption(Option.SOCKET_TIMEOUT, socketTimeout); // Reload the client implementations Options.refresh(); } /** * Set the concurrency levels * * @param maxTotal Defines the overall connection limit for a connection pool. Default is 200. * @param maxPerRoute Defines a connection limit per one HTTP route (this can be considered a per target host limit). Default is 20. */ public static void setConcurrency(int maxTotal, int maxPerRoute) { Options.setOption(Option.MAX_TOTAL, maxTotal); Options.setOption(Option.MAX_PER_ROUTE, maxPerRoute); // Reload the client implementations Options.refresh(); } /** * Clear default headers */ public static void clearDefaultHeaders() { Options.setOption(Option.DEFAULT_HEADERS, null); } /** * Set default header */ @SuppressWarnings("unchecked") public static void setDefaultHeader(String name, String value) { Object headers = Options.getOption(Option.DEFAULT_HEADERS); if (headers == null) { headers = new HashMap(); } ((Map) headers).put(name, value); Options.setOption(Option.DEFAULT_HEADERS, headers); } /** * Close the asynchronous client and its event loop. Use this method to close all the threads and allow an application to exit. */ public static void shutdown() throws IOException { // Closing the Sync HTTP client CloseableHttpClient syncClient = (CloseableHttpClient) Options.getOption(Option.HTTPCLIENT); if (syncClient != null) { syncClient.close(); } SyncIdleConnectionMonitorThread syncIdleConnectionMonitorThread = (SyncIdleConnectionMonitorThread) Options.getOption(Option.SYNC_MONITOR); if (syncIdleConnectionMonitorThread != null) { syncIdleConnectionMonitorThread.interrupt(); } // Closing the Async HTTP client (if running) CloseableHttpAsyncClient asyncClient = (CloseableHttpAsyncClient) Options.getOption(Option.ASYNCHTTPCLIENT); if (asyncClient != null && asyncClient.isRunning()) { asyncClient.close(); } AsyncIdleConnectionMonitorThread asyncMonitorThread = (AsyncIdleConnectionMonitorThread) Options.getOption(Option.ASYNC_MONITOR); if (asyncMonitorThread != null) { asyncMonitorThread.interrupt(); } } public static GetRequest get(String url) { return new GetRequest(HttpMethod.GET, url); } public static GetRequest head(String url) { return new GetRequest(HttpMethod.HEAD, url); } public static HttpRequestWithBody options(String url) { return new HttpRequestWithBody(HttpMethod.OPTIONS, url); } public static HttpRequestWithBody post(String url) { return new HttpRequestWithBody(HttpMethod.POST, url); } public static HttpRequestWithBody delete(String url) { return new HttpRequestWithBody(HttpMethod.DELETE, url); } public static HttpRequestWithBody patch(String url) { return new HttpRequestWithBody(HttpMethod.PATCH, url); } public static HttpRequestWithBody put(String url) { return new HttpRequestWithBody(HttpMethod.PUT, url); } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/async/000077500000000000000000000000001265451610200271615ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/async/Callback.java000066400000000000000000000025421265451610200315230ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.http.async; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.exceptions.UnirestException; public interface Callback { void completed(HttpResponse response); void failed(UnirestException e); void cancelled(); } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/async/RequestThread.java000066400000000000000000000036461265451610200326150ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.http.async; import com.mashape.unirest.http.HttpClientHelper; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.exceptions.UnirestException; import com.mashape.unirest.request.HttpRequest; public class RequestThread extends Thread { private HttpRequest httpRequest; private Class responseClass; private Callback callback; public RequestThread(HttpRequest httpRequest, Class responseClass, Callback callback) { this.httpRequest = httpRequest; this.responseClass = responseClass; this.callback = callback; } @Override public void run() { HttpResponse response; try { response = HttpClientHelper.request(httpRequest, responseClass); if (callback != null) { callback.completed(response); } } catch (UnirestException e) { callback.failed(e); } } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/async/utils/000077500000000000000000000000001265451610200303215ustar00rootroot00000000000000AsyncIdleConnectionMonitorThread.java000066400000000000000000000015421265451610200375020ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/async/utilspackage com.mashape.unirest.http.async.utils; import java.util.concurrent.TimeUnit; import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; public class AsyncIdleConnectionMonitorThread extends Thread { private final PoolingNHttpClientConnectionManager connMgr; public AsyncIdleConnectionMonitorThread(PoolingNHttpClientConnectionManager connMgr) { super(); super.setDaemon(true); this.connMgr = connMgr; } @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { synchronized (this) { wait(5000); // Close expired connections connMgr.closeExpiredConnections(); // Optionally, close connections // that have been idle longer than 30 sec connMgr.closeIdleConnections(30, TimeUnit.SECONDS); } } } catch (InterruptedException ex) { // terminate } } }unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/exceptions/000077500000000000000000000000001265451610200302255ustar00rootroot00000000000000UnirestException.java000066400000000000000000000004321265451610200343200ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/exceptionspackage com.mashape.unirest.http.exceptions; public class UnirestException extends Exception { private static final long serialVersionUID = -3714840499934575734L; public UnirestException(Exception e) { super(e); } public UnirestException(String msg) { super(msg); } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/options/000077500000000000000000000000001265451610200275375ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/options/Option.java000066400000000000000000000003411265451610200316500ustar00rootroot00000000000000package com.mashape.unirest.http.options; public enum Option { HTTPCLIENT, ASYNCHTTPCLIENT, CONNECTION_TIMEOUT, SOCKET_TIMEOUT, DEFAULT_HEADERS, SYNC_MONITOR, ASYNC_MONITOR, MAX_TOTAL, MAX_PER_ROUTE, PROXY, OBJECT_MAPPER } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/options/Options.java000066400000000000000000000077151265451610200320470ustar00rootroot00000000000000package com.mashape.unirest.http.options; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.nio.reactor.IOReactorException; import com.mashape.unirest.http.async.utils.AsyncIdleConnectionMonitorThread; import com.mashape.unirest.http.utils.SyncIdleConnectionMonitorThread; public class Options { public static final long CONNECTION_TIMEOUT = 10000; private static final long SOCKET_TIMEOUT = 60000; public static final int MAX_TOTAL = 200; public static final int MAX_PER_ROUTE = 20; private static Map options = new HashMap(); private static boolean customClientSet = false; public static void customClientSet() { customClientSet = true; } public static void setOption(Option option, Object value) { if ((option == Option.CONNECTION_TIMEOUT || option == Option.SOCKET_TIMEOUT) && customClientSet) { throw new RuntimeException("You can't set custom timeouts when providing custom client implementations. Set the timeouts directly in your custom client configuration instead."); } options.put(option, value); } public static Object getOption(Option option) { return options.get(option); } static { refresh(); } public static void refresh() { // Load timeouts Object connectionTimeout = Options.getOption(Option.CONNECTION_TIMEOUT); if (connectionTimeout == null) connectionTimeout = CONNECTION_TIMEOUT; Object socketTimeout = Options.getOption(Option.SOCKET_TIMEOUT); if (socketTimeout == null) socketTimeout = SOCKET_TIMEOUT; // Load limits Object maxTotal = Options.getOption(Option.MAX_TOTAL); if (maxTotal == null) maxTotal = MAX_TOTAL; Object maxPerRoute = Options.getOption(Option.MAX_PER_ROUTE); if (maxPerRoute == null) maxPerRoute = MAX_PER_ROUTE; // Load proxy if set HttpHost proxy = (HttpHost) Options.getOption(Option.PROXY); // Create common default configuration RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(((Long) connectionTimeout).intValue()).setSocketTimeout(((Long) socketTimeout).intValue()).setConnectionRequestTimeout(((Long) socketTimeout).intValue()).setProxy(proxy).build(); PoolingHttpClientConnectionManager syncConnectionManager = new PoolingHttpClientConnectionManager(); syncConnectionManager.setMaxTotal((Integer) maxTotal); syncConnectionManager.setDefaultMaxPerRoute((Integer) maxPerRoute); // Create clients setOption(Option.HTTPCLIENT, HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).setConnectionManager(syncConnectionManager).build()); SyncIdleConnectionMonitorThread syncIdleConnectionMonitorThread = new SyncIdleConnectionMonitorThread(syncConnectionManager); setOption(Option.SYNC_MONITOR, syncIdleConnectionMonitorThread); syncIdleConnectionMonitorThread.start(); DefaultConnectingIOReactor ioreactor; PoolingNHttpClientConnectionManager asyncConnectionManager; try { ioreactor = new DefaultConnectingIOReactor(); asyncConnectionManager = new PoolingNHttpClientConnectionManager(ioreactor); asyncConnectionManager.setMaxTotal((Integer) maxTotal); asyncConnectionManager.setDefaultMaxPerRoute((Integer) maxPerRoute); } catch (IOReactorException e) { throw new RuntimeException(e); } CloseableHttpAsyncClient asyncClient = HttpAsyncClientBuilder.create().setDefaultRequestConfig(clientConfig).setConnectionManager(asyncConnectionManager).build(); setOption(Option.ASYNCHTTPCLIENT, asyncClient); setOption(Option.ASYNC_MONITOR, new AsyncIdleConnectionMonitorThread(asyncConnectionManager)); } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/utils/000077500000000000000000000000001265451610200272045ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/utils/Base64Coder.java000066400000000000000000000223161265451610200320540ustar00rootroot00000000000000package com.mashape.unirest.http.utils; //Copyright 2003-2010 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland //www.source-code.biz, www.inventec.ch/chdh // //This module is multi-licensed and may be used under the terms //of any of the following licenses: // //EPL, Eclipse Public License, V1.0 or later, http://www.eclipse.org/legal //LGPL, GNU Lesser General Public License, V2.1 or later, http://www.gnu.org/licenses/lgpl.html //GPL, GNU General Public License, V2 or later, http://www.gnu.org/licenses/gpl.html //AL, Apache License, V2.0 or later, http://www.apache.org/licenses //BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php //MIT, MIT License, http://www.opensource.org/licenses/MIT // //Please contact the author if you need another license. //This module is provided "as is", without warranties of any kind. /** * A Base64 encoder/decoder. * *

* This class is used to encode and decode data in Base64 format as described in RFC 1521. * *

* Project home page: www.source-code.biz/base64coder/java
* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
* Multi-licensed: EPL / LGPL / GPL / AL / BSD / MIT. */ public class Base64Coder { // The line separator string of the operating system. private static final String systemLineSeparator = System.getProperty("line.separator"); // Mapping table from 6-bit nibbles to Base64 characters. private static final char[] map1 = new char[64]; static { int i = 0; for (char c = 'A'; c <= 'Z'; c++) map1[i++] = c; for (char c = 'a'; c <= 'z'; c++) map1[i++] = c; for (char c = '0'; c <= '9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; } // Mapping table from Base64 characters to 6-bit nibbles. private static final byte[] map2 = new byte[128]; static { for (int i = 0; i < map2.length; i++) map2[i] = -1; for (int i = 0; i < 64; i++) map2[map1[i]] = (byte) i; } /** * Encodes a string into Base64 format. No blanks or line breaks are inserted. * * @param s A String to be encoded. * @return A String containing the Base64 encoded data. */ public static String encodeString(String s) { return new String(encode(s.getBytes())); } /** * Encodes a byte array into Base 64 format and breaks the output into lines of 76 characters. This method is compatible with * sun.misc.BASE64Encoder.encodeBuffer(byte[]). * * @param in An array containing the data bytes to be encoded. * @return A String containing the Base64 encoded data, broken into lines. */ public static String encodeLines(byte[] in) { return encodeLines(in, 0, in.length, 76, systemLineSeparator); } /** * Encodes a byte array into Base 64 format and breaks the output into lines. * * @param in An array containing the data bytes to be encoded. * @param iOff Offset of the first byte in in to be processed. * @param iLen Number of bytes to be processed in in, starting at iOff. * @param lineLen Line length for the output data. Should be a multiple of 4. * @param lineSeparator The line separator to be used to separate the output lines. * @return A String containing the Base64 encoded data, broken into lines. */ public static String encodeLines(byte[] in, int iOff, int iLen, int lineLen, String lineSeparator) { int blockLen = (lineLen * 3) / 4; if (blockLen <= 0) throw new IllegalArgumentException(); int lines = (iLen + blockLen - 1) / blockLen; int bufLen = ((iLen + 2) / 3) * 4 + lines * lineSeparator.length(); StringBuilder buf = new StringBuilder(bufLen); int ip = 0; while (ip < iLen) { int l = Math.min(iLen - ip, blockLen); buf.append(encode(in, iOff + ip, l)); buf.append(lineSeparator); ip += l; } return buf.toString(); } /** * Encodes a byte array into Base64 format. No blanks or line breaks are inserted in the output. * * @param in An array containing the data bytes to be encoded. * @return A character array containing the Base64 encoded data. */ public static char[] encode(byte[] in) { return encode(in, 0, in.length); } /** * Encodes a byte array into Base64 format. No blanks or line breaks are inserted in the output. * * @param in An array containing the data bytes to be encoded. * @param iLen Number of bytes to process in in. * @return A character array containing the Base64 encoded data. */ public static char[] encode(byte[] in, int iLen) { return encode(in, 0, iLen); } /** * Encodes a byte array into Base64 format. No blanks or line breaks are inserted in the output. * * @param in An array containing the data bytes to be encoded. * @param iOff Offset of the first byte in in to be processed. * @param iLen Number of bytes to process in in, starting at iOff. * @return A character array containing the Base64 encoded data. */ public static char[] encode(byte[] in, int iOff, int iLen) { int oDataLen = (iLen * 4 + 2) / 3; // output length without padding int oLen = ((iLen + 2) / 3) * 4; // output length including padding char[] out = new char[oLen]; int ip = iOff; int iEnd = iOff + iLen; int op = 0; while (ip < iEnd) { int i0 = in[ip++] & 0xff; int i1 = ip < iEnd ? in[ip++] & 0xff : 0; int i2 = ip < iEnd ? in[ip++] & 0xff : 0; int o0 = i0 >>> 2; int o1 = ((i0 & 3) << 4) | (i1 >>> 4); int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); int o3 = i2 & 0x3F; out[op++] = map1[o0]; out[op++] = map1[o1]; out[op] = op < oDataLen ? map1[o2] : '='; op++; out[op] = op < oDataLen ? map1[o3] : '='; op++; } return out; } /** * Decodes a string from Base64 format. No blanks or line breaks are allowed within the Base64 encoded input data. * * @param s A Base64 String to be decoded. * @return A String containing the decoded data. * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ public static String decodeString(String s) { return new String(decode(s)); } /** * Decodes a byte array from Base64 format and ignores line separators, tabs and blanks. CR, LF, Tab and Space characters are ignored in the input data. This method is * compatible with sun.misc.BASE64Decoder.decodeBuffer(String). * * @param s A Base64 String to be decoded. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ public static byte[] decodeLines(String s) { char[] buf = new char[s.length()]; int p = 0; for (int ip = 0; ip < s.length(); ip++) { char c = s.charAt(ip); if (c != ' ' && c != '\r' && c != '\n' && c != '\t') buf[p++] = c; } return decode(buf, 0, p); } /** * Decodes a byte array from Base64 format. No blanks or line breaks are allowed within the Base64 encoded input data. * * @param s A Base64 String to be decoded. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ public static byte[] decode(String s) { return decode(s.toCharArray()); } /** * Decodes a byte array from Base64 format. No blanks or line breaks are allowed within the Base64 encoded input data. * * @param in A character array containing the Base64 encoded data. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ public static byte[] decode(char[] in) { return decode(in, 0, in.length); } /** * Decodes a byte array from Base64 format. No blanks or line breaks are allowed within the Base64 encoded input data. * * @param in A character array containing the Base64 encoded data. * @param iOff Offset of the first character in in to be processed. * @param iLen Number of characters to process in in, starting at iOff. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException If the input is not valid Base64 encoded data. */ public static byte[] decode(char[] in, int iOff, int iLen) { if (iLen % 4 != 0) throw new IllegalArgumentException("Length of Base64 encoded input string is not a multiple of 4."); while (iLen > 0 && in[iOff + iLen - 1] == '=') iLen--; int oLen = (iLen * 3) / 4; byte[] out = new byte[oLen]; int ip = iOff; int iEnd = iOff + iLen; int op = 0; while (ip < iEnd) { int i0 = in[ip++]; int i1 = in[ip++]; int i2 = ip < iEnd ? in[ip++] : 'A'; int i3 = ip < iEnd ? in[ip++] : 'A'; if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) throw new IllegalArgumentException("Illegal character in Base64 encoded data."); int b0 = map2[i0]; int b1 = map2[i1]; int b2 = map2[i2]; int b3 = map2[i3]; if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) throw new IllegalArgumentException("Illegal character in Base64 encoded data."); int o0 = (b0 << 2) | (b1 >>> 4); int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2); int o2 = ((b2 & 3) << 6) | b3; out[op++] = (byte) o0; if (op < oLen) out[op++] = (byte) o1; if (op < oLen) out[op++] = (byte) o2; } return out; } // Dummy constructor. private Base64Coder() { } } // end class Base64Coderunirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/utils/ClientFactory.java000066400000000000000000000010251265451610200326130ustar00rootroot00000000000000package com.mashape.unirest.http.utils; import org.apache.http.client.HttpClient; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import com.mashape.unirest.http.options.Option; import com.mashape.unirest.http.options.Options; public class ClientFactory { public static HttpClient getHttpClient() { return (HttpClient) Options.getOption(Option.HTTPCLIENT); } public static CloseableHttpAsyncClient getAsyncHttpClient() { return (CloseableHttpAsyncClient) Options.getOption(Option.ASYNCHTTPCLIENT); } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/utils/MapUtil.java000066400000000000000000000037141265451610200314270ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.http.utils; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; public class MapUtil { public static List getList(Map> parameters) { List result = new ArrayList(); if (parameters != null) { TreeMap> sortedParameters = new TreeMap>(parameters); for (Entry> entry : sortedParameters.entrySet()) { List entryValue = entry.getValue(); if (entryValue != null) { for (Object cur : entryValue) { if (cur != null) { result.add(new BasicNameValuePair(entry.getKey(), cur.toString())); } } } } } return result; } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/utils/ResponseUtils.java000066400000000000000000000030411265451610200326640ustar00rootroot00000000000000package com.mashape.unirest.http.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.Header; public class ResponseUtils { private static final Pattern charsetPattern = Pattern.compile("(?i)\\bcharset=\\s*\"?([^\\s;\"]*)"); /** * Parse out a charset from a content type header. * * @param contentType e.g. "text/html; charset=EUC-JP" * @return "EUC-JP", or null if not found. Charset is trimmed and uppercased. */ public static String getCharsetFromContentType(String contentType) { if (contentType == null) return null; Matcher m = charsetPattern.matcher(contentType); if (m.find()) { return m.group(1).trim().toUpperCase(); } return null; } public static byte[] getBytes(InputStream is) throws IOException { int len; int size = 1024; byte[] buf; if (is instanceof ByteArrayInputStream) { size = is.available(); buf = new byte[size]; len = is.read(buf, 0, size); } else { ByteArrayOutputStream bos = new ByteArrayOutputStream(); buf = new byte[size]; while ((len = is.read(buf, 0, size)) != -1) bos.write(buf, 0, len); buf = bos.toByteArray(); } return buf; } public static boolean isGzipped(Header contentEncoding) { if (contentEncoding != null) { String value = contentEncoding.getValue(); if (value != null && "gzip".equals(value.toLowerCase().trim())) { return true; } } return false; } } SyncIdleConnectionMonitorThread.java000066400000000000000000000014711265451610200362250ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/utilspackage com.mashape.unirest.http.utils; import java.util.concurrent.TimeUnit; import org.apache.http.conn.HttpClientConnectionManager; public class SyncIdleConnectionMonitorThread extends Thread { private final HttpClientConnectionManager connMgr; public SyncIdleConnectionMonitorThread(HttpClientConnectionManager connMgr) { super(); super.setDaemon(true); this.connMgr = connMgr; } @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { synchronized (this) { wait(5000); // Close expired connections connMgr.closeExpiredConnections(); // Optionally, close connections // that have been idle longer than 30 sec connMgr.closeIdleConnections(30, TimeUnit.SECONDS); } } } catch (InterruptedException ex) { // terminate } } }unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/utils/URLParamEncoder.java000066400000000000000000000033201265451610200327700ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.http.utils; public class URLParamEncoder { public static String encode(String input) { StringBuilder resultStr = new StringBuilder(); for (char ch : input.toCharArray()) { if (isUnsafe(ch)) { resultStr.append('%'); resultStr.append(toHex(ch / 16)); resultStr.append(toHex(ch % 16)); } else { resultStr.append(ch); } } return resultStr.toString(); } private static char toHex(int ch) { return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10); } private static boolean isUnsafe(char ch) { if (ch > 128 || ch < 0) return true; return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0; } }unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/request/000077500000000000000000000000001265451610200265555ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/request/BaseRequest.java000066400000000000000000000070611265451610200316470ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.request; import com.mashape.unirest.http.HttpClientHelper; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.async.Callback; import com.mashape.unirest.http.exceptions.UnirestException; import java.io.InputStream; import java.util.concurrent.Future; public abstract class BaseRequest { protected static final String UTF_8 = "UTF-8"; protected HttpRequest httpRequest; protected BaseRequest(HttpRequest httpRequest) { this.httpRequest = httpRequest; } public HttpRequest getHttpRequest() { return this.httpRequest; } protected BaseRequest() { super(); } public HttpResponse asString() throws UnirestException { return HttpClientHelper.request(httpRequest, String.class); } public Future> asStringAsync() { return HttpClientHelper.requestAsync(httpRequest, String.class, null); } public Future> asStringAsync(Callback callback) { return HttpClientHelper.requestAsync(httpRequest, String.class, callback); } public HttpResponse asJson() throws UnirestException { return HttpClientHelper.request(httpRequest, JsonNode.class); } public Future> asJsonAsync() { return HttpClientHelper.requestAsync(httpRequest, JsonNode.class, null); } public Future> asJsonAsync(Callback callback) { return HttpClientHelper.requestAsync(httpRequest, JsonNode.class, callback); } public HttpResponse asObject(Class responseClass) throws UnirestException { return HttpClientHelper.request(httpRequest, (Class) responseClass); } public Future> asObjectAsync(Class responseClass) { return HttpClientHelper.requestAsync(httpRequest, (Class) responseClass, null); } public Future> asObjectAsync(Class responseClass, Callback callback) { return HttpClientHelper.requestAsync(httpRequest, (Class) responseClass, callback); } public HttpResponse asBinary() throws UnirestException { return HttpClientHelper.request(httpRequest, InputStream.class); } public Future> asBinaryAsync() { return HttpClientHelper.requestAsync(httpRequest, InputStream.class, null); } public Future> asBinaryAsync(Callback callback) { return HttpClientHelper.requestAsync(httpRequest, InputStream.class, callback); } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/request/GetRequest.java000066400000000000000000000034241265451610200315130ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.request; import java.util.Map; import com.mashape.unirest.http.HttpMethod; public class GetRequest extends HttpRequest { public GetRequest(HttpMethod method, String url) { super(method, url); } public GetRequest routeParam(String name, String value) { super.routeParam(name, value); return this; } @Override public GetRequest header(String name, String value) { return (GetRequest) super.header(name, value); } @Override public GetRequest headers(Map headers) { return (GetRequest) super.headers(headers); } @Override public GetRequest basicAuth(String username, String password) { super.basicAuth(username, password); return this; } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/request/HttpRequest.java000066400000000000000000000107121265451610200317110ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.request; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.mashape.unirest.http.HttpMethod; import com.mashape.unirest.http.utils.Base64Coder; import com.mashape.unirest.http.utils.URLParamEncoder; import com.mashape.unirest.request.body.Body; public class HttpRequest extends BaseRequest { private HttpMethod httpMethod; protected String url; Map> headers = new TreeMap>(String.CASE_INSENSITIVE_ORDER); protected Body body; public HttpRequest(HttpMethod method, String url) { this.httpMethod = method; this.url = url; super.httpRequest = this; } public HttpRequest routeParam(String name, String value) { Matcher matcher = Pattern.compile("\\{" + name + "\\}").matcher(url); int count = 0; while (matcher.find()) { count++; } if (count == 0) { throw new RuntimeException("Can't find route parameter name \"" + name + "\""); } this.url = url.replaceAll("\\{" + name + "\\}", URLParamEncoder.encode(value)); return this; } public HttpRequest basicAuth(String username, String password) { header("Authorization", "Basic " + Base64Coder.encodeString(username + ":" + password)); return this; } public HttpRequest header(String name, String value) { List list = this.headers.get(name.trim()); if (list == null) { list = new ArrayList(); } list.add(value); this.headers.put(name.trim(), list); return this; } public HttpRequest headers(Map headers) { if (headers != null) { for (Map.Entry entry : headers.entrySet()) { header(entry.getKey(), entry.getValue()); } } return this; } public HttpRequest queryString(String name, Collection value) { for (Object cur : value) { queryString(name, cur); } return this; } public HttpRequest queryString(String name, Object value) { StringBuilder queryString = new StringBuilder(); if (this.url.contains("?")) { queryString.append("&"); } else { queryString.append("?"); } try { queryString .append(URLEncoder.encode(name)) .append("=") .append(URLEncoder.encode((value == null) ? "" : value.toString(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } this.url += queryString.toString(); return this; } public HttpRequest queryString(Map parameters) { if (parameters != null) { for (Entry param : parameters.entrySet()) { if (param.getValue() instanceof String || param.getValue() instanceof Number || param.getValue() instanceof Boolean) { queryString(param.getKey(), param.getValue()); } else { throw new RuntimeException("Parameter \"" + param.getKey() + "\" can't be sent with a GET request because of type: " + param.getValue().getClass().getName()); } } } return this; } public HttpMethod getHttpMethod() { return httpMethod; } public String getUrl() { return url; } public Map> getHeaders() { if (headers == null) return new HashMap>(); return headers; } public Body getBody() { return body; } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/request/HttpRequestWithBody.java000066400000000000000000000130621265451610200333640ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.request; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.content.InputStreamBody; import com.mashape.unirest.http.HttpMethod; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.ObjectMapper; import com.mashape.unirest.http.options.Option; import com.mashape.unirest.http.options.Options; import com.mashape.unirest.request.body.MultipartBody; import com.mashape.unirest.request.body.RawBody; import com.mashape.unirest.request.body.RequestBodyEntity; import org.json.JSONArray; import org.json.JSONObject; import java.io.File; import java.io.InputStream; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; public class HttpRequestWithBody extends HttpRequest { public HttpRequestWithBody(HttpMethod method, String url) { super(method, url); } @Override public HttpRequestWithBody routeParam(String name, String value) { super.routeParam(name, value); return this; } @Override public HttpRequestWithBody header(String name, String value) { return (HttpRequestWithBody) super.header(name, value); } @Override public HttpRequestWithBody headers(Map headers) { return (HttpRequestWithBody) super.headers(headers); } @Override public HttpRequestWithBody basicAuth(String username, String password) { super.basicAuth(username, password); return this; } @Override public HttpRequestWithBody queryString(Map parameters) { return (HttpRequestWithBody) super.queryString(parameters); } @Override public HttpRequestWithBody queryString(String name, Object value) { return (HttpRequestWithBody) super.queryString(name, value); } public MultipartBody field(String name, Collection value) { MultipartBody body = new MultipartBody(this).field(name, value); this.body = body; return body; } public MultipartBody field(String name, Object value) { return field(name, value, null); } public MultipartBody field(String name, File file) { return field(name, file, null); } public MultipartBody field(String name, Object value, String contentType) { MultipartBody body = new MultipartBody(this).field(name, (value == null) ? "" : value.toString(), contentType); this.body = body; return body; } public MultipartBody field(String name, File file, String contentType) { MultipartBody body = new MultipartBody(this).field(name, file, contentType); this.body = body; return body; } public MultipartBody fields(Map parameters) { MultipartBody body = new MultipartBody(this); if (parameters != null) { for (Entry param : parameters.entrySet()) { if (param.getValue() instanceof File) { body.field(param.getKey(), (File) param.getValue()); } else { body.field(param.getKey(), (param.getValue() == null) ? "" : param.getValue().toString()); } } } this.body = body; return body; } public MultipartBody field(String name, InputStream stream, ContentType contentType, String fileName) { InputStreamBody inputStreamBody = new InputStreamBody(stream, contentType, fileName); MultipartBody body = new MultipartBody(this).field(name, inputStreamBody, true, contentType.toString()); this.body = body; return body; } public MultipartBody field(String name, InputStream stream, String fileName) { MultipartBody body = field(name, stream, ContentType.APPLICATION_OCTET_STREAM, fileName); this.body = body; return body; } public RequestBodyEntity body(JsonNode body) { return body(body.toString()); } public RequestBodyEntity body(String body) { RequestBodyEntity b = new RequestBodyEntity(this).body(body); this.body = b; return b; } public RequestBodyEntity body(Object body) { ObjectMapper objectMapper = (ObjectMapper) Options.getOption(Option.OBJECT_MAPPER); if (objectMapper == null) { throw new RuntimeException("Serialization Impossible. Can't find an ObjectMapper implementation."); } return body(objectMapper.writeValue(body)); } public RawBody body(byte[] body) { RawBody b = new RawBody(this).body(body); this.body = b; return b; } /** * Sugar method for body operation * * @param body raw org.JSONObject * @return RequestBodyEntity instance */ public RequestBodyEntity body(JSONObject body) { return body(body.toString()); } /** * Sugar method for body operation * * @param body raw org.JSONArray * @return RequestBodyEntity instance */ public RequestBodyEntity body(JSONArray body) { return body(body.toString()); } }unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/request/body/000077500000000000000000000000001265451610200275125ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/request/body/Body.java000066400000000000000000000023151265451610200312530ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.request.body; import org.apache.http.HttpEntity; public interface Body { HttpEntity getEntity(); } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/request/body/MultipartBody.java000066400000000000000000000141331265451610200331560ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.request.body; import java.io.File; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.LinkedHashMap; import org.apache.http.HttpEntity; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.ByteArrayBody; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.InputStreamBody; import org.apache.http.entity.mime.content.StringBody; import com.mashape.unirest.http.utils.MapUtil; import com.mashape.unirest.request.BaseRequest; import com.mashape.unirest.request.HttpRequest; public class MultipartBody extends BaseRequest implements Body { private Map> parameters = new LinkedHashMap>(); private Map contentTypes = new HashMap(); private boolean hasFile; private HttpRequest httpRequestObj; private HttpMultipartMode mode; public MultipartBody(HttpRequest httpRequest) { super(httpRequest); this.httpRequestObj = httpRequest; } public MultipartBody field(String name, String value) { return field(name, value, false, null); } public MultipartBody field(String name, String value, String contentType) { return field(name, value, false, contentType); } public MultipartBody field(String name, Collection collection) { for (Object current : collection) { boolean isFile = current instanceof File; field(name, current, isFile, null); } return this; } public MultipartBody field(String name, Object value) { return field(name, value, false, null); } public MultipartBody field(String name, Object value, boolean file) { return field(name, value, file, null); } public MultipartBody field(String name, Object value, boolean file, String contentType) { List list = parameters.get(name); if (list == null) list = new LinkedList(); list.add(value); parameters.put(name, list); ContentType type = null; if (contentType != null && contentType.length() > 0) { type = ContentType.parse(contentType); } else if (file) { type = ContentType.APPLICATION_OCTET_STREAM; } else { type = ContentType.APPLICATION_FORM_URLENCODED.withCharset(UTF_8); } contentTypes.put(name, type); if (!hasFile && file) { hasFile = true; } return this; } public MultipartBody field(String name, File file) { return field(name, file, true, null); } public MultipartBody field(String name, File file, String contentType) { return field(name, file, true, contentType); } public MultipartBody field(String name, InputStream stream, ContentType contentType, String fileName) { return field(name, new InputStreamBody(stream, contentType, fileName), true, contentType.getMimeType()); } public MultipartBody field(String name, InputStream stream, String fileName) { return field(name, new InputStreamBody(stream, ContentType.APPLICATION_OCTET_STREAM, fileName), true, ContentType.APPLICATION_OCTET_STREAM.getMimeType()); } public MultipartBody field(String name, byte[] bytes, ContentType contentType, String fileName) { return field(name, new ByteArrayBody(bytes, contentType, fileName), true, contentType.getMimeType()); } public MultipartBody field(String name, byte[] bytes, String fileName) { return field(name, new ByteArrayBody(bytes, ContentType.APPLICATION_OCTET_STREAM, fileName), true, ContentType.APPLICATION_OCTET_STREAM.getMimeType()); } public MultipartBody basicAuth(String username, String password) { httpRequestObj.basicAuth(username, password); return this; } public MultipartBody mode(String mode) { this.mode = HttpMultipartMode.valueOf(mode); return this; } public HttpEntity getEntity() { if (hasFile) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (mode != null) { builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); } for (String key : parameters.keySet()) { List value = parameters.get(key); ContentType contentType = contentTypes.get(key); for (Object cur : value) { if (cur instanceof File) { File file = (File) cur; builder.addPart(key, new FileBody(file, contentType, file.getName())); } else if (cur instanceof InputStreamBody) { builder.addPart(key, (ContentBody) cur); } else if (cur instanceof ByteArrayBody) { builder.addPart(key, (ContentBody) cur); } else { builder.addPart(key, new StringBody(cur.toString(), contentType)); } } } return builder.build(); } else { try { return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } } unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/request/body/RawBody.java000066400000000000000000000032021265451610200317210ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.request.body; import com.mashape.unirest.request.BaseRequest; import com.mashape.unirest.request.HttpRequest; import org.apache.http.HttpEntity; import org.apache.http.entity.ByteArrayEntity; public class RawBody extends BaseRequest implements Body { private byte[] body; public RawBody(HttpRequest httpRequest) { super(httpRequest); } public RawBody body(byte[] body) { this.body = body; return this; } public Object getBody() { return body; } public HttpEntity getEntity() { return new ByteArrayEntity(body); } } RequestBodyEntity.java000066400000000000000000000034721265451610200337470ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/request/body/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.request.body; import org.apache.http.HttpEntity; import org.apache.http.entity.StringEntity; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.request.BaseRequest; import com.mashape.unirest.request.HttpRequest; public class RequestBodyEntity extends BaseRequest implements Body { private Object body; public RequestBodyEntity(HttpRequest httpRequest) { super(httpRequest); } public RequestBodyEntity body(String body) { this.body = body; return this; } public RequestBodyEntity body(JsonNode body) { this.body = body.toString(); return this; } public Object getBody() { return body; } public HttpEntity getEntity() { return new StringEntity(body.toString(), UTF_8); } } unirest-java-unirest-java-1.4.8/src/test/000077500000000000000000000000001265451610200203125ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/test/java/000077500000000000000000000000001265451610200212335ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/test/java/com/000077500000000000000000000000001265451610200220115ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/test/java/com/mashape/000077500000000000000000000000001265451610200234275ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/test/java/com/mashape/unirest/000077500000000000000000000000001265451610200251205ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/test/java/com/mashape/unirest/test/000077500000000000000000000000001265451610200260775ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/test/java/com/mashape/unirest/test/helper/000077500000000000000000000000001265451610200273565ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/test/java/com/mashape/unirest/test/helper/GetResponse.java000066400000000000000000000005701265451610200324610ustar00rootroot00000000000000package com.mashape.unirest.test.helper; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class GetResponse { @JsonProperty("url") private String url; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } JacksonObjectMapper.java000066400000000000000000000013571265451610200340340ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/test/java/com/mashape/unirest/test/helperpackage com.mashape.unirest.test.helper; import com.fasterxml.jackson.core.JsonProcessingException; import com.mashape.unirest.http.ObjectMapper; import java.io.IOException; public class JacksonObjectMapper implements ObjectMapper { private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); public T readValue(String value, Class valueType) { try { return jacksonObjectMapper.readValue(value, valueType); } catch (IOException e) { throw new RuntimeException(e); } } public String writeValue(Object value) { try { return jacksonObjectMapper.writeValueAsString(value); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } } unirest-java-unirest-java-1.4.8/src/test/java/com/mashape/unirest/test/http/000077500000000000000000000000001265451610200270565ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/test/java/com/mashape/unirest/test/http/UnirestTest.java000066400000000000000000000773531265451610200322310ustar00rootroot00000000000000/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mashape.unirest.test.http; import com.mashape.unirest.http.*; import com.mashape.unirest.http.async.Callback; import com.mashape.unirest.http.exceptions.UnirestException; import com.mashape.unirest.http.options.Options; import com.mashape.unirest.request.GetRequest; import com.mashape.unirest.request.HttpRequest; import com.mashape.unirest.test.helper.GetResponse; import com.mashape.unirest.test.helper.JacksonObjectMapper; import org.apache.commons.io.IOUtils; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import java.io.*; import java.net.InetAddress; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.Arrays; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.*; public class UnirestTest { private CountDownLatch lock; private boolean status; @Before public void setUp() { lock = new CountDownLatch(1); status = false; } private String findAvailableIpAddress() throws UnknownHostException, IOException { for (int i = 100; i <= 255; i++) { String ip = "192.168.1." + i; if (!InetAddress.getByName(ip).isReachable(1000)) { return ip; } } throw new RuntimeException("Couldn't find an available IP address in the range of 192.168.0.100-255"); } @Test public void testRequests() throws JSONException, UnirestException { HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); } @Test public void testGet() throws JSONException, UnirestException { HttpResponse response = Unirest.get("http://httpbin.org/get?name=mark").asJson(); assertEquals(response.getBody().getObject().getJSONObject("args").getString("name"), "mark"); response = Unirest.get("http://httpbin.org/get").queryString("name", "mark2").asJson(); assertEquals(response.getBody().getObject().getJSONObject("args").getString("name"), "mark2"); } @Test public void testGetUTF8() throws UnirestException { HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("param3", "こんにちは").asJson(); assertEquals(response.getBody().getObject().getJSONObject("args").getString("param3"), "こんにちは"); } @Test public void testPostUTF8() throws UnirestException { HttpResponse response = Unirest.post("http://httpbin.org/post").field("param3", "こんにちは").asJson(); assertEquals(response.getBody().getObject().getJSONObject("form").getString("param3"), "こんにちは"); } @Test public void testPostBinaryUTF8() throws UnirestException, URISyntaxException { HttpResponse response = Unirest.post("http://httpbin.org/post").field("param3", "こんにちは").field("file", new File(getClass().getResource("/test").toURI())).asJson(); assertEquals("This is a test file", response.getBody().getObject().getJSONObject("files").getString("file")); assertEquals("こんにちは", response.getBody().getObject().getJSONObject("form").getString("param3")); } @Test public void testPostRawBody() throws UnirestException, URISyntaxException, IOException { String sourceString = "'\"@こんにちは-test-123-" + Math.random(); byte[] sentBytes = sourceString.getBytes(); HttpResponse response = Unirest.post("http://httpbin.org/post").body(sentBytes).asJson(); assertEquals(sourceString, response.getBody().getObject().getString("data")); } @Test public void testCustomUserAgent() throws JSONException, UnirestException { HttpResponse response = Unirest.get("http://httpbin.org/get?name=mark").header("user-agent", "hello-world").asJson(); assertEquals("hello-world", response.getBody().getObject().getJSONObject("headers").getString("User-Agent")); GetRequest getRequest = Unirest.get("http"); for (Object current : Arrays.asList(0, 1, 2)) { getRequest.queryString("name", current); } } @Test public void testGetMultiple() throws JSONException, UnirestException { for (int i = 1; i <= 20; i++) { HttpResponse response = Unirest.get("http://httpbin.org/get?try=" + i).asJson(); assertEquals(response.getBody().getObject().getJSONObject("args").getString("try"), ((Integer) i).toString()); } } @Test public void testGetFields() throws JSONException, UnirestException { HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", "mark").queryString("nick", "thefosk").asJson(); assertEquals(response.getBody().getObject().getJSONObject("args").getString("name"), "mark"); assertEquals(response.getBody().getObject().getJSONObject("args").getString("nick"), "thefosk"); } @Test public void testGetFields2() throws JSONException, UnirestException { HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("email", "hello@hello.com").asJson(); assertEquals("hello@hello.com", response.getBody().getObject().getJSONObject("args").getString("email")); } @Test public void testQueryStringEncoding() throws JSONException, UnirestException { String testKey = "email2=someKey&email"; String testValue = "hello@hello.com"; HttpResponse response = Unirest.get("http://httpbin.org/get").queryString(testKey, testValue).asJson(); assertEquals(testValue, response.getBody().getObject().getJSONObject("args").getString(testKey)); } @Test public void testDelete() throws JSONException, UnirestException { HttpResponse response = Unirest.delete("http://httpbin.org/delete").asJson(); assertEquals(200, response.getStatus()); response = Unirest.delete("http://httpbin.org/delete").field("name", "mark").asJson(); assertEquals("mark", response.getBody().getObject().getJSONObject("form").getString("name")); } @Test public void testDeleteBody() throws JSONException, UnirestException { String body = "{\"jsonString\":{\"members\":\"members1\"}}"; HttpResponse response = Unirest.delete("http://httpbin.org/delete").body(body).asJson(); assertEquals(200, response.getStatus()); assertEquals(body, response.getBody().getObject().getString("data")); } @Test public void testBasicAuth() throws JSONException, UnirestException { HttpResponse response = Unirest.get("http://httpbin.org/headers").basicAuth("user", "test").asJson(); assertEquals("Basic dXNlcjp0ZXN0", response.getBody().getObject().getJSONObject("headers").getString("Authorization")); } @Test public void testAsync() throws JSONException, InterruptedException, ExecutionException { Future> future = Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJsonAsync(); assertNotNull(future); HttpResponse jsonResponse = future.get(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); } @Test public void testAsyncCallback() throws JSONException, InterruptedException, ExecutionException { Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJsonAsync(new Callback() { public void failed(UnirestException e) { fail(); } public void completed(HttpResponse jsonResponse) { assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertEquals("value1", json.getObject().getJSONObject("form").getString("param1")); assertEquals("bye", json.getObject().getJSONObject("form").getString("param2")); status = true; lock.countDown(); } public void cancelled() { fail(); } }); lock.await(10, TimeUnit.SECONDS); assertTrue(status); } @Test public void testMultipart() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException { HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/test").toURI())).asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertNotNull(json.getObject().getJSONObject("files")); assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); } @Test public void testMultipartContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException { HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/image.jpg").toURI()), "image/jpeg").asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertNotNull(json.getObject().getJSONObject("files")); assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:image/jpeg")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); } @Test public void testMultipartInputStreamContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, FileNotFoundException { HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())), ContentType.APPLICATION_OCTET_STREAM, "image.jpg").asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertNotNull(json.getObject().getJSONObject("files")); assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:application/octet-stream")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); } @Test public void testMultipartInputStreamContentTypeAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, FileNotFoundException { Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new FileInputStream(new File(getClass().getResource("/test").toURI())), ContentType.APPLICATION_OCTET_STREAM, "test").asJsonAsync(new Callback() { public void failed(UnirestException e) { fail(); } public void completed(HttpResponse response) { assertTrue(response.getHeaders().size() > 0); assertTrue(response.getBody().toString().length() > 0); assertFalse(response.getRawBody() == null); assertEquals(200, response.getStatus()); JsonNode json = response.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); status = true; lock.countDown(); } public void cancelled() { fail(); } }); lock.await(10, TimeUnit.SECONDS); assertTrue(status); } @Test public void testMultipartByteContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, IOException { final InputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); final byte[] bytes = new byte[stream.available()]; stream.read(bytes); stream.close(); HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", bytes, "image.jpg").asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertNotNull(json.getObject().getJSONObject("files")); assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:application/octet-stream")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); } @Test public void testMultipartByteContentTypeAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, IOException { final InputStream stream = new FileInputStream(new File(getClass().getResource("/test").toURI())); final byte[] bytes = new byte[stream.available()]; stream.read(bytes); stream.close(); Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", bytes, "test").asJsonAsync(new Callback() { public void failed(UnirestException e) { fail(); } public void completed(HttpResponse response) { assertTrue(response.getHeaders().size() > 0); assertTrue(response.getBody().toString().length() > 0); assertFalse(response.getRawBody() == null); assertEquals(200, response.getStatus()); JsonNode json = response.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); status = true; lock.countDown(); } public void cancelled() { fail(); } }); lock.await(10, TimeUnit.SECONDS); assertTrue(status); } @Test public void testMultipartAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException { Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/test").toURI())).asJsonAsync(new Callback() { public void failed(UnirestException e) { fail(); } public void completed(HttpResponse response) { assertTrue(response.getHeaders().size() > 0); assertTrue(response.getBody().toString().length() > 0); assertFalse(response.getRawBody() == null); assertEquals(200, response.getStatus()); JsonNode json = response.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); status = true; lock.countDown(); } public void cancelled() { fail(); } }); lock.await(10, TimeUnit.SECONDS); assertTrue(status); } @Test public void testGzip() throws UnirestException, JSONException { HttpResponse jsonResponse = Unirest.get("http://httpbin.org/gzip").asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertTrue(json.getObject().getBoolean("gzipped")); } @Test public void testGzipAsync() throws UnirestException, JSONException, InterruptedException, ExecutionException { HttpResponse jsonResponse = Unirest.get("http://httpbin.org/gzip").asJsonAsync().get(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertTrue(json.getObject().getBoolean("gzipped")); } @Test public void testDefaultHeaders() throws UnirestException, JSONException { Unirest.setDefaultHeader("X-Custom-Header", "hello"); Unirest.setDefaultHeader("user-agent", "foobar"); HttpResponse jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); assertEquals("hello", json.getObject().getJSONObject("headers").getString("X-Custom-Header")); assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("User-Agent")); assertEquals("foobar", json.getObject().getJSONObject("headers").getString("User-Agent")); jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); assertEquals("hello", jsonResponse.getBody().getObject().getJSONObject("headers").getString("X-Custom-Header")); Unirest.clearDefaultHeaders(); jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); assertFalse(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); } @Test public void testSetTimeouts() throws UnknownHostException, IOException { String address = "http://" + findAvailableIpAddress() + "/"; long start = System.currentTimeMillis(); try { Unirest.get("http://" + address + "/").asString(); } catch (Exception e) { if (System.currentTimeMillis() - start > Options.CONNECTION_TIMEOUT + 100) { // Add 100ms for code execution fail(); } } Unirest.setTimeouts(2000, 10000); start = System.currentTimeMillis(); try { Unirest.get("http://" + address + "/").asString(); } catch (Exception e) { if (System.currentTimeMillis() - start > 2100) { // Add 100ms for code execution fail(); } } } @Test public void testPathParameters() throws UnirestException { HttpResponse jsonResponse = Unirest.get("http://httpbin.org/{method}").routeParam("method", "get").queryString("name", "Mark").asJson(); assertEquals(200, jsonResponse.getStatus()); assertEquals(jsonResponse.getBody().getObject().getJSONObject("args").getString("name"), "Mark"); } @Test public void testQueryAndBodyParameters() throws UnirestException { HttpResponse jsonResponse = Unirest.post("http://httpbin.org/{method}").routeParam("method", "post").queryString("name", "Mark").field("wot", "wat").asJson(); assertEquals(200, jsonResponse.getStatus()); assertEquals(jsonResponse.getBody().getObject().getJSONObject("args").getString("name"), "Mark"); assertEquals(jsonResponse.getBody().getObject().getJSONObject("form").getString("wot"), "wat"); } @Test public void testPathParameters2() throws UnirestException { HttpResponse jsonResponse = Unirest.patch("http://httpbin.org/{method}").routeParam("method", "patch").field("name", "Mark").asJson(); assertEquals(200, jsonResponse.getStatus()); assertEquals("OK", jsonResponse.getStatusText()); assertEquals(jsonResponse.getBody().getObject().getJSONObject("form").getString("name"), "Mark"); } @Test public void testMissingPathParameter() throws UnirestException { try { Unirest.get("http://httpbin.org/{method}").routeParam("method222", "get").queryString("name", "Mark").asJson(); fail(); } catch (RuntimeException e) { // OK } } @Test public void parallelTest() throws InterruptedException { Unirest.setConcurrency(10, 5); long start = System.currentTimeMillis(); makeParallelRequests(); long smallerConcurrencyTime = (System.currentTimeMillis() - start); Unirest.setConcurrency(200, 20); start = System.currentTimeMillis(); makeParallelRequests(); long higherConcurrencyTime = (System.currentTimeMillis() - start); assertTrue(higherConcurrencyTime < smallerConcurrencyTime); } private void makeParallelRequests() throws InterruptedException { ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10); final AtomicInteger counter = new AtomicInteger(0); for (int i = 0; i < 200; i++) { newFixedThreadPool.execute(new Runnable() { public void run() { try { Unirest.get("http://httpbin.org/get").queryString("index", counter.incrementAndGet()).asJson(); } catch (UnirestException e) { throw new RuntimeException(e); } } }); } newFixedThreadPool.shutdown(); newFixedThreadPool.awaitTermination(10, TimeUnit.MINUTES); } @Test public void testAsyncCustomContentType() throws InterruptedException { Unirest.post("http://httpbin.org/post").header("accept", "application/json").header("Content-Type", "application/json").body("{\"hello\":\"world\"}").asJsonAsync(new Callback() { public void failed(UnirestException e) { fail(); } public void completed(HttpResponse jsonResponse) { JsonNode json = jsonResponse.getBody(); assertEquals("{\"hello\":\"world\"}", json.getObject().getString("data")); assertEquals("application/json", json.getObject().getJSONObject("headers").getString("Content-Type")); status = true; lock.countDown(); } public void cancelled() { fail(); } }); lock.await(10, TimeUnit.SECONDS); assertTrue(status); } @Test public void testAsyncCustomContentTypeAndFormParams() throws InterruptedException { Unirest.post("http://httpbin.org/post").header("accept", "application/json").header("Content-Type", "application/x-www-form-urlencoded").field("name", "Mark").field("hello", "world").asJsonAsync(new Callback() { public void failed(UnirestException e) { fail(); } public void completed(HttpResponse jsonResponse) { JsonNode json = jsonResponse.getBody(); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); assertEquals("world", json.getObject().getJSONObject("form").getString("hello")); assertEquals("application/x-www-form-urlencoded", json.getObject().getJSONObject("headers").getString("Content-Type")); status = true; lock.countDown(); } public void cancelled() { fail(); } }); lock.await(10, TimeUnit.SECONDS); assertTrue(status); } @Test public void testGetQuerystringArray() throws JSONException, UnirestException { HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", "Mark").queryString("name", "Tom").asJson(); JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); assertEquals(2, names.length()); assertEquals("Mark", names.getString(0)); assertEquals("Tom", names.getString(1)); } @Test public void testPostMultipleFiles() throws JSONException, UnirestException, URISyntaxException { HttpResponse response = Unirest.post("http://httpbin.org/post").field("param3", "wot").field("file1", new File(getClass().getResource("/test").toURI())).field("file2", new File(getClass().getResource("/test").toURI())).asJson(); JSONObject names = response.getBody().getObject().getJSONObject("files"); assertEquals(2, names.length()); assertEquals("This is a test file", names.getString("file1")); assertEquals("This is a test file", names.getString("file2")); assertEquals("wot", response.getBody().getObject().getJSONObject("form").getString("param3")); } @Test public void testGetArray() throws JSONException, UnirestException { HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", Arrays.asList("Mark", "Tom")).asJson(); JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); assertEquals(2, names.length()); assertEquals("Mark", names.getString(0)); assertEquals("Tom", names.getString(1)); } @Test public void testPostArray() throws JSONException, UnirestException { HttpResponse response = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("name", "Tom").asJson(); JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); assertEquals(2, names.length()); assertEquals("Mark", names.getString(0)); assertEquals("Tom", names.getString(1)); } @Test public void testPostCollection() throws JSONException, UnirestException { HttpResponse response = Unirest.post("http://httpbin.org/post").field("name", Arrays.asList("Mark", "Tom")).asJson(); JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); assertEquals(2, names.length()); assertEquals("Mark", names.getString(0)); assertEquals("Tom", names.getString(1)); } @Test public void testCaseInsensitiveHeaders() throws UnirestException { GetRequest request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); JSONObject headers = request.asJson().getBody().getObject().getJSONObject("headers"); assertEquals("Marco", headers.getString("Name")); request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco").header("Name", "John"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("John", request.getHeaders().get("name").get(1)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("John", request.getHeaders().get("NAme").get(1)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); assertEquals("John", request.getHeaders().get("Name").get(1)); headers = request.asJson().getBody().getObject().getJSONObject("headers"); assertEquals("Marco,John", headers.get("Name")); } @Test public void setTimeoutsAndCustomClient() { try { Unirest.setTimeouts(1000, 2000); } catch (Exception e) { fail(); } try { Unirest.setAsyncHttpClient(HttpAsyncClientBuilder.create().build()); } catch (Exception e) { fail(); } try { Unirest.setAsyncHttpClient(HttpAsyncClientBuilder.create().build()); Unirest.setTimeouts(1000, 2000); fail(); } catch (Exception e) { // Ok } try { Unirest.setHttpClient(HttpClientBuilder.create().build()); Unirest.setTimeouts(1000, 2000); fail(); } catch (Exception e) { // Ok } } @Test public void testObjectMapperRead() throws UnirestException, IOException { Unirest.setObjectMapper(new JacksonObjectMapper()); GetResponse getResponseMock = new GetResponse(); getResponseMock.setUrl("http://httpbin.org/get"); HttpResponse getResponse = Unirest.get(getResponseMock.getUrl()).asObject(GetResponse.class); assertEquals(200, getResponse.getStatus()); assertEquals(getResponse.getBody().getUrl(), getResponseMock.getUrl()); } @Test public void testObjectMapperWrite() throws UnirestException, IOException { Unirest.setObjectMapper(new JacksonObjectMapper()); GetResponse postResponseMock = new GetResponse(); postResponseMock.setUrl("http://httpbin.org/post"); HttpResponse postResponse = Unirest.post(postResponseMock.getUrl()).header("accept", "application/json").header("Content-Type", "application/json").body(postResponseMock).asJson(); assertEquals(200, postResponse.getStatus()); assertEquals(postResponse.getBody().getObject().getString("data"), "{\"url\":\"http://httpbin.org/post\"}"); } @Test public void testPostProvidesSortedParams() throws IOException { // Verify that fields are encoded into the body in sorted order. HttpRequest httpRequest = Unirest.post("test").field("z", "Z").field("y", "Y").field("x", "X").getHttpRequest(); InputStream content = httpRequest.getBody().getEntity().getContent(); String body = IOUtils.toString(content, "UTF-8"); assertEquals("x=X&y=Y&z=Z", body); } @Test public void testHeaderNamesCaseSensitive() { // Verify that header names are the same as server (case sensitive) final Headers headers = new Headers(); headers.put("Content-Type", Arrays.asList("application/json")); assertEquals("Only header \"Content-Type\" should exist", null, headers.getFirst("cOnTeNt-TyPe")); assertEquals("Only header \"Content-Type\" should exist", null, headers.getFirst("content-type")); assertEquals("Only header \"Content-Type\" should exist", "application/json", headers.getFirst("Content-Type")); } } unirest-java-unirest-java-1.4.8/src/test/resources/000077500000000000000000000000001265451610200223245ustar00rootroot00000000000000unirest-java-unirest-java-1.4.8/src/test/resources/image.jpg000066400000000000000000000117451265451610200241200ustar00rootroot00000000000000JFIF``C     C   m  DDB88888hqqq4 s88hqqqs@8889DD(89xzqqq8889qpqq889c@889qcGGq8889qqq1q9D{q8889c@88qq9Gчs@::89qqqq884As@888qqq88s,1qqqs@888hqqqNc9qqq8889c@889a888qqq8888U8889qqqs@888Nc+888qqqqqq41aqq4 hqqq8889q088hqqq48889qcÎ88qq0qqs@8qs@888qqq88㞎e8hqqqs@889c@8)q8889qqq88898qqq4888hqqqkqqq888hs@88Hmqqq4888hqqq=@8<=8qqq4888DDsqqq4::884888"#88qqq48889B""988qqq4 9qqq1􈈎w88qqq4888hDDDsqs@888qqq48""#8qqs@Ɓqqq9興}8qqq889qR"""#qqq8889qcqqqs@Ɓqqq8DDDDGqq8888恍8}""""#`88h888hqqdDDDDG@8hq8ӎ8> 0ADADDDD " """ "" DADADDADD "" "    DDADDDDDAA_0DDDAAADAAD`    """""""   "" " # "" ""  " " " " "" " " " """"""" ""  " " " " "" "" ""   "   #   "   < ""    ""< "" " "H""""" "  " B" " """  ADAADDAADAd "" " "  ADADDAAAAAA" " """ """" DDDAAADAD   " AAAAADA "  " "DADDAADADAB"" "  AADAAADDDA " " DADDAADADt """""""#?I_?I_?I_ 0!@?!cF;GF9hv*9jG#1Tr1#c1QcF1#cюG#5G<x;F15UG#UTvьvьv|jvr;G#vGh92<r1F1<*;G#|0#r9F;GhQr;_F1F1r9G#vcr;F1vG#v5Gh{#vG#cTy;F<Gc#vcjG#Q9uTxjTy1UUG#T}jQ<TcQlv9F1яQ#NG#cvhcG#c1F1F9QGh#cьr<5UF9cvzGh5GNJx*9G#c=UG#cPr1NJcG9G5G#cUQ9#Q1ccuTc#rz#c99r91#1c1c1cǧ II I $@$I@ $I$I$I$ I I I$I $I$ $I$I@$HH $I$I$I$I$I$$H H$I$HdI H $@I$I$I$ I $II $I$I$I I @I$HI$@ $I i$I I $HA$@I$I$I$I$H H $@I$I$I$H$$I $H $ $HII$H$I $@ $I$ $I$I II A $@$I$@I$I$I$I$I HI$HA$@ $$I$I$I $I$H $I$I$ I$$I$$@$I$II$@I$I$H H@M$$I$?I_?I_1 !a0A@?IHDD( (D̈(&"$"\&@ I(0$D=1 eP&P:? J$G*@0xB ᦂ&Ax"D 5jDI\Q ,@@Dka*( B*A2"DPDP$G x dP&(H4Tqbȉ0&QO @jPT& "DJLy?@&)EP$E@(? H(D(< "SHjUG$DD "(HaI\UBALP aQ"~(4UP"5ȕL)HDDdR GP.L@.H*"%j@2DQ($PxBQ"Aʠ&"Sd("DpH0a|T DWPJ‹"5_!&XD Dd0"cX @ (`E(x CQ"ƃL$QUPPEElԪlѨS#A=D)MmL 0l=qQ?L0p L096` `0 0p`b `ᆱunirest-java-unirest-java-1.4.8/src/test/resources/test000066400000000000000000000000231265451610200232210ustar00rootroot00000000000000This is a test file