最简单的java http client api

Life is short , play more!
本文来自lihao's Blog,转载请注明。

你还在使用apache http client, 倒也没什么. 但你肯定也很纠结, 功能虽太强大,但使用起来并不简单.

快来试用一下 Java HTTP Request Library https://github.com/kevinsawicki/http-request

这个库的目的是为了让我们编写http请求的时候, 和使用httpurlconnection 一样. 但功能却不弱.

Apache HttpComponents 使用起来还是相对复杂一些, 比如在android中, 如果使用 java http request library , 那么实在是太便捷了.

一些例子: 如果你觉得好, 那么就可以尝试下来替代apache httpcomponents .

执行get请求,并获得返回code(例如是200,还是400)

int response = HttpRequest.get("http://google.com").code();

执行get请求,并获得返回得body体.

String response = HttpRequest.get("http://google.com").body();
System.out.println("Response was: " + response);

打印get请求到控制台上

HttpRequest.get("http://google.com").receive(System.out);

添加get请求, get请求为(  getrequest?parameter=value&parameter2=value)

HttpRequest request = HttpRequest.get("http://google.com", true, 'q', "baseball gloves", "size", 100);
System.out.println(request.toString()); // GET http://google.com?q=baseball%20gloves&size=100

request/reponse 头的处理

String contentType = HttpRequest.get("http://google.com")
                                .accept("application/json") //Sets request header
                                .contentType(); //Gets response header
System.out.println("Response content type was " + contentType);

post请求

 

int response = HttpRequest.post("http://google.com").send("name=kevin").code();

基本认证

int response = HttpRequest.get("http://google.com").basic("username", "p4ssw0rd").code();

执行multipast post 操作 (官网上的有问题,请注意标红色地方,需要加上该参数)

HttpRequest request = HttpRequest.post("http://google.com");
request.part("status[body]", "Making a multipart request");
request.part("status[image]", "ide.png", new File("/home/kevin/Pictures/ide.png"));
if (request.ok())
  System.out.println("Status was updated");

执行post请求, post的内容为form表单

Map<String, String> data = new HashMap<String, String>();
data.put("user", "A User");
data.put("state", "CA");
if (HttpRequest.post("http://google.com").form(data).created())
  System.out.println("User was created");

将请求的返回的body 保存到一个文件

File output = new File("/output/request.out");
HttpRequest.get("http://google.com").receive(output);

post的请求的body为一个文件内容

File input = new File("/input/data.txt");
int response = HttpRequest.post("http://google.com").send(input).code();

实体标签为缓存

File latest = new File("/data/cache.json");
HttpRequest request = HttpRequest.get("http://google.com");
//Copy response to file
request.receive(latest);
//Store eTag of response
String eTag = request.eTag();
//Later on check if changes exist
boolean unchanged = HttpRequest.get("http://google.com")
                               .ifNoneMatch(eTag)
                               .notModified();

使用gzip

HttpRequest request = HttpRequest.get("http://google.com");
//Tell server to gzip response and automatically uncompress
request.acceptGzipEncoding().uncompress(true);
String uncompressed = request.body();
System.out.println("Uncompressed response is: " + uncompressed);

当试用https时

HttpRequest request = HttpRequest.get("https://google.com");
//Accept all certificates
request.trustAllCerts();
//Accept all hostnames
request.trustAllHosts();

配置http代理

HttpRequest request = HttpRequest.get("https://google.com");
//Configure proxy
request.useProxy("localhost", 8080);
//Optional proxy basic authentication
request.proxyBasic("username", "p4ssw0rd");

允许重定向

int code = HttpRequest.get("http://google.com").followRedirects(true).code();

自定义http工厂

更多的信息请访问 OkHttp? 并阅读 here.

HttpRequest.setConnectionFactory(new ConnectionFactory() {

  public HttpURLConnection create(URL url) throws IOException {
    if (!"https".equals(url.getProtocol()))
      throw new IOException("Only secure requests are allowed");
    return (HttpURLConnection) url.openConnection();
  }

  public HttpURLConnection create(URL url, Proxy proxy) throws IOException {
    if (!"https".equals(url.getProtocol()))
      throw new IOException("Only secure requests are allowed");
    return (HttpURLConnection) url.openConnection(proxy);
  }
});

 


发表评论

电子邮件地址不会被公开。 必填项已用*标注