輕量級http開發庫Unirest
一. 特點
可以被PHP、Ruby、Python、Java、Objective-C等語言調用
支持GET、POST、PUT、UPDATE、DELETE操作,調用方法和返回類型對所有語言都是相同的
可以利用下面代碼發送httprequest
Unirest.post("http://httpbin.org/post")
.queryString("name", "Mark")
.field("last", "Polo")
.asJson()
特點:
- 請求:GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
- 異步+同步模式
- 支持表單參數、文件上傳
- gzip、基本的本地認證、proxy、timeout
- 默認headers、HttpClient、HttpAsyncClient、轉json
maven
<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.9</version>
</dependency>
二. 使用
創建request
基本的post請求
HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
.header("accept", "application/json")
.queryString("apiKey", "123")
.field("parameter", "value")
.field("foo", "bar")
.asJson();
當執行了asType方法之后,Requests就被生成了,可以轉換的內容為Json, Binary, String, Object
.body(String|JsonNode|Object),當使用.body(Object) 時需要額外的配置參數
.fields(Map<String, Object> fields)會把每個k-v填入form表單
.headers(Map<String, String> headers)填入headers參數
Serialization
當執行asObject(Class)或者.body(Object)之前,需要一個ObjectMapper的定制實現,在最初就要運行,因為ObjectMapper是全局共享的
比如使用Jackson序列化json,如下
// Only one time
Unirest.setObjectMapper(new ObjectMapper() {
private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper
= new com.fasterxml.jackson.databind.ObjectMapper();
public <T> T readValue(String value, Class<T> 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<Book> bookResponse = Unirest.get("http://httpbin.org/books/1").asObject(Book.class);
Book bookObject = bookResponse.getBody();
HttpResponse<Author> authorResponse = Unirest.get("http://httpbin.org/books/{id}/author")
.routeParam("id", bookObject.getId())
.asObject(Author.class);
Author authorObject = authorResponse.getBody();
// Object to Json
HttpResponse<JsonNode> postResponse = Unirest.post("http://httpbin.org/authors/post")
.header("accept", "application/json")
.header("Content-Type", "application/json")
.body(authorObject)
.asJson();
Route Parameters
在RUL中添加動態參數,可以通過URL中添加占位符,然后再利用routeParam函數
Unirest.get("http://httpbin.org/{method}")
.routeParam("method", "get")
.queryString("name", "Mark")
.asJson();
這里的占位符會被get代替
異步請求
很多時候,需要使用asynchronous模式,使用異步回調
Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post")
.header("accept", "application/json")
.field("param1", "value1")
.field("param2", "value2")
.asJsonAsync(new Callback<JsonNode>() {
public void failed(UnirestException e) {
System.out.println("The request has failed");
}
public void completed(HttpResponse<JsonNode> response) {
int code = response.getStatus();
Map<String, String> headers = response.getHeaders();
JsonNode body = response.getBody();
InputStream rawBody = response.getRawBody();
}
public void cancelled() {
System.out.println("The request has been cancelled");
}
});
文件上傳
使用java創建multipart請求很瑣碎,下面代碼簡化這一個過程
HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
.header("accept", "application/json")
.field("parameter", "value")
.field("file", new File("/tmp/file"))
.asJson();
定制實體body
HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
.header("accept", "application/json")
.body("{\"parameter\":\"value\", \"foo\":\"bar\"}")
.asJson();
比特流body
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<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
.field("name", "Mark")
.field("file", bytes, "image.jpg")
.asJson();
InputStream body
HttpResponse<JsonNode> 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
調用basicAuth(username, password)
HttpResponse<JsonNode> response =
Unirest.get("http://httpbin.org/headers").basicAuth("username", "password").asJson();
三. Request & Response
Java版本的是構造這模式,通過下面這些方式獲取HttpRequest
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);
收到反饋時,返回一個Object,object對於不同的語言應該有相同的keys
.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
四. 高級配置
可以設置一些高級的配置,調整Unirest
定制HTTP clients,可以修改HttpClient和HttpAsyncClient的實現,然后設置進Unirest中
Unirest.setHttpClient(httpClient);
Unirest.setAsyncHttpClient(asyncHttpClient);
Timeouts以ms為單位
默認連接超時10000,socket超時60000,設置為0為關閉
Unirest.setTimeouts(long connectionTimeout, long socketTimeout);
默認的Request Headers,每個request都會發出去
Unirest.setDefaultHeader("Header1", "Value1");
Unirest.setDefaultHeader("Header2", "Value2");
清除默認的頭
Unirest.clearDefaultHeaders();
並發,可以設置並發級別,通過設置同步或者異步的client
默認pool中全部的連接限制,maxTotal設置為200,並且maxPerRoute目標host設置為20
Unirest.setConcurrency(int maxTotal, int maxPerRoute);
代理
Unirest.setProxy(new HttpHost("127.0.0.1", 8000));
退出應用
Unirest開啟后台一個event loop,需要手動調用執行退出
Unirest.shutdown();
python使用的例子
http://www.open-open.com/lib/view/open1415237017090.html
