pax_global_header 0000666 0000000 0000000 00000000064 12654516102 0014514 g ustar 00root root 0000000 0000000 52 comment=6f3e56e8dae9479f5c8a9f121834ecc99ed5e76d
unirest-java-unirest-java-1.4.8/ 0000775 0000000 0000000 00000000000 12654516102 0016544 5 ustar 00root root 0000000 0000000 unirest-java-unirest-java-1.4.8/.editorconfig 0000664 0000000 0000000 00000000371 12654516102 0021222 0 ustar 00root root 0000000 0000000 # 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/.gitignore 0000664 0000000 0000000 00000000156 12654516102 0020536 0 ustar 00root root 0000000 0000000 .classpath
pom.xml.releaseBackup
.project
target
.DS_Store
.settings
release.properties
META-INF
.idea
*.iml
unirest-java-unirest-java-1.4.8/.travis.yml 0000664 0000000 0000000 00000000134 12654516102 0020653 0 ustar 00root root 0000000 0000000 language: java
jdk:
- openjdk6
- openjdk7
- oraclejdk7
- oraclejdk8
os:
- linux
unirest-java-unirest-java-1.4.8/LICENSE 0000664 0000000 0000000 00000002113 12654516102 0017546 0 ustar 00root root 0000000 0000000 The 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.md 0000664 0000000 0000000 00000031040 12654516102 0020021 0 ustar 00root root 0000000 0000000 # 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.unirestunirest-java1.4.8
```
There are dependencies for Unirest-Java, these should be already installed, and they are as follows:
```xml
org.apache.httpcomponentshttpclient4.3.6org.apache.httpcomponentshttpasyncclient4.0.2org.apache.httpcomponentshttpmime4.3.6org.jsonjson20140107
```
If you would like to run tests, also add the following dependency along with the others:
```xml
junitjunit4.11testcommons-iocommons-io2.4test
```
### 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/deploy 0000775 0000000 0000000 00000000614 12654516102 0017767 0 ustar 00root root 0000000 0000000 #!/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/ 0000775 0000000 0000000 00000000000 12654516102 0020547 5 ustar 00root root 0000000 0000000 unirest-java-unirest-java-1.4.8/formatter/unirest-code-format.xml 0000664 0000000 0000000 00000075034 12654516102 0025171 0 ustar 00root root 0000000 0000000
unirest-java-unirest-java-1.4.8/pom.xml 0000664 0000000 0000000 00000007563 12654516102 0020074 0 ustar 00root root 0000000 0000000
4.0.0com.mashape.unirestunirest-javajar1.4.8unirest-javaSimplified, lightweight HTTP client libraryhttp://unirest.io/org.sonatype.ossoss-parent7MIThttp://opensource.org/licenses/MITrepohttps://github.com/Mashape/unirest-javascm:git:git@github.com:Mashape/unirest-java.gitscm:git:git@github.com:Mashape/unirest-java.gitmashapeMashapeopensource@mashape.comhttps://github.com/MashapeMashapehttps://www.mashape.comUTF-8UTF-82.6.0org.apache.maven.pluginsmaven-compiler-plugin3.1true128m512m1.51.5UTF-8org.apache.maven.pluginsmaven-assembly-plugin2.4jar-with-dependenciesorg.apache.maven.pluginsmaven-source-plugin2.2.1attach-sourcesjarorg.apache.maven.pluginsmaven-javadoc-plugin2.9.1attach-javadocsjarorg.apache.httpcomponentshttpclient4.3.6org.apache.httpcomponentshttpasyncclient4.0.2org.apache.httpcomponentshttpmime4.3.6org.jsonjson20140107junitjunit4.12testcommons-iocommons-io2.4testcom.fasterxml.jackson.corejackson-databind${jackson.version}test
unirest-java-unirest-java-1.4.8/src/ 0000775 0000000 0000000 00000000000 12654516102 0017333 5 ustar 00root root 0000000 0000000 unirest-java-unirest-java-1.4.8/src/main/ 0000775 0000000 0000000 00000000000 12654516102 0020257 5 ustar 00root root 0000000 0000000 unirest-java-unirest-java-1.4.8/src/main/java/ 0000775 0000000 0000000 00000000000 12654516102 0021200 5 ustar 00root root 0000000 0000000 unirest-java-unirest-java-1.4.8/src/main/java/com/ 0000775 0000000 0000000 00000000000 12654516102 0021756 5 ustar 00root root 0000000 0000000 unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/ 0000775 0000000 0000000 00000000000 12654516102 0023374 5 ustar 00root root 0000000 0000000 unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/ 0000775 0000000 0000000 00000000000 12654516102 0025065 5 ustar 00root root 0000000 0000000 unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/ 0000775 0000000 0000000 00000000000 12654516102 0026044 5 ustar 00root root 0000000 0000000 unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/Headers.java 0000664 0000000 0000000 00000000566 12654516102 0030271 0 ustar 00root root 0000000 0000000 package 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.java 0000664 0000000 0000000 00000020544 12654516102 0032132 0 ustar 00root root 0000000 0000000 /*
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.java 0000664 0000000 0000000 00000003111 12654516102 0032417 0 ustar 00root root 0000000 0000000 /*
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.java 0000664 0000000 0000000 00000002266 12654516102 0030775 0 ustar 00root root 0000000 0000000 /*
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.java 0000664 0000000 0000000 00000003104 12654516102 0032256 0 ustar 00root root 0000000 0000000 /*
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.java 0000664 0000000 0000000 00000011023 12654516102 0031342 0 ustar 00root root 0000000 0000000 /*
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.java 0000664 0000000 0000000 00000004257 12654516102 0030436 0 ustar 00root root 0000000 0000000 /*
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.java 0000664 0000000 0000000 00000000235 12654516102 0031262 0 ustar 00root root 0000000 0000000 package 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.java 0000664 0000000 0000000 00000014266 12654516102 0030351 0 ustar 00root root 0000000 0000000 /*
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/ 0000775 0000000 0000000 00000000000 12654516102 0027161 5 ustar 00root root 0000000 0000000 unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/async/Callback.java 0000664 0000000 0000000 00000002542 12654516102 0031523 0 ustar 00root root 0000000 0000000 /*
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.java 0000664 0000000 0000000 00000003646 12654516102 0032615 0 ustar 00root root 0000000 0000000 /*
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/ 0000775 0000000 0000000 00000000000 12654516102 0030321 5 ustar 00root root 0000000 0000000 AsyncIdleConnectionMonitorThread.java 0000664 0000000 0000000 00000001542 12654516102 0037502 0 ustar 00root root 0000000 0000000 unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/async/utils package 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/ 0000775 0000000 0000000 00000000000 12654516102 0030225 5 ustar 00root root 0000000 0000000 UnirestException.java 0000664 0000000 0000000 00000000432 12654516102 0034320 0 ustar 00root root 0000000 0000000 unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/exceptions package 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/ 0000775 0000000 0000000 00000000000 12654516102 0027537 5 ustar 00root root 0000000 0000000 unirest-java-unirest-java-1.4.8/src/main/java/com/mashape/unirest/http/options/Option.java 0000664 0000000 0000000 00000000341 12654516102 0031650 0 ustar 00root root 0000000 0000000 package 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.java 0000664 0000000 0000000 00000007715 12654516102 0032047 0 ustar 00root root 0000000 0000000 package 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