一个基于HttpURLConnection简单方便的创建HTTP请求并接收响应数据的工具库.
在MIT License可以获取到该库
http-request这个库可以从Maven Central获取.
<dependency>
<groupId>com.github.kevinsawicki</groupId>
<artifactId>http-request</artifactId>
<version>6.0</version>
</dependency>不使用Maven? 只要复制 HttpRequest 类到你的工种当中, 更新包的报名,然后你就可以使用它了.
你可以从 这里.获取到javadoc文档
这里是已知的项目使用该库
写这个库是为了在使用HttpURLConnection来发送HTTP请求的时候更加方便快捷
像Apache HttpComponents这样的组件也是非常好用的,但是有些时候为了更加简单,或者可能因为你部署的环境的问题(比如Android),你只想使用例如HttpURLConnection一些过时但是又好用的库。
这个库寻找一种更加方便和一种更加通用的模式来模拟HTTP请求,并支持多种特性的请求,例如多个请求的任务.
没有. 整个库只有单一的一个类和一些静态的内部类,测试工程需要Jetty的支持,用来实现一个真实的HTTP服务器请求来测试请求.
HttpRequest类不抛出任何检查异常,相反的,所有低等级的异常被包装在继承了RuntimeException类的HttpRequestException中,你可以通过catchingHttpRequestException以及调用getCause方法来获取潜在的异常信息,它总会返回最原始的IOException
不是. 每个HttpRequest对象都包装了HttpUrlConnection这个最根本的对象的一个同步API,因此,所有在HttpRequest对象中的方法都是同步的。
因此,不要在你的应用程序的主线程中使用HttpRequest对象是非常关键的.
这有一个在Android上使用的小例子 AsyncTask:
private class DownloadTask extends AsyncTask<String, Long, File> {
protected File doInBackground(String... urls) {
try {
HttpRequest request = HttpRequest.get(urls[0]);
File file = null;
if (request.ok()) {
file = File.createTempFile("download", ".tmp");
request.receive(file);
publishProgress(file.length());
}
return file;
} catch (HttpRequestException exception) {
return null;
}
}
protected void onProgressUpdate(Long... progress) {
Log.d("MyApp", "Downloaded bytes: " + progress[0]);
}
protected void onPostExecute(File file) {
if (file != null)
Log.d("MyApp", "Downloaded file to: " + file.getAbsolutePath());
else
Log.d("MyApp", "Download failed");
}
}
new DownloadTask().execute("http://google.com");int response = HttpRequest.get("http://google.com").code();String response = HttpRequest.get("http://google.com").body();
System.out.println("Response was: " + response);HttpRequest.get("http://google.com").receive(System.out);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=100int[] ids = new int[] { 22, 23 };
HttpRequest request = HttpRequest.get("http://google.com", true, "id", ids);
System.out.println(request.toString()); // GET http://google.com?id[]=22&id[]=23String body = HttpRequest.put("http://google.com")
.contentType(HttpRequest.CONTENT_TYPE_JSON).send(jsonString.getBytes()).body();
System.out.println(body);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);int response = HttpRequest.post("http://google.com").send("name=kevin").code();int response = HttpRequest.get("http://google.com").basic("username", "p4ssw0rd").code();HttpRequest request = HttpRequest.post("http://google.com");
request.part("status[body]", "Making a multipart request");
request.part("status[image]", new File("/home/kevin/Pictures/ide.png"));
if (request.ok())
System.out.println("Status was updated");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");File output = new File("/output/request.out");
HttpRequest.get("http://google.com").receive(output);File input = new File("/input/data.txt");
int response = HttpRequest.post("http://google.com").send(input).code();String base64 = base64(t[i].getAbsolutePath());
String body = HttpRequest.post(url)
.part("base64Strs", new ByteArrayInputStream(base64.getBytes())).body();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();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);HttpRequest request = HttpRequest.get("https://google.com");
//Accept all certificates
request.trustAllCerts();
//Accept all hostnames
request.trustAllHosts();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();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);
}
});- Kevin Sawicki :: contributions
- Eddie Ringle :: contributions
- Sean Jensen-Grey :: contributions
- Levi Notik :: contributions
- Michael Wang :: contributions
- Julien HENRY :: contributions
- Benoit Lubek :: contributions
- Jake Wharton :: contributions
- Oskar Hagberg :: contributions
- David Pate :: contributions
- Anton Rieder :: contributions
- Jean-Baptiste Lièvremont :: contributions
- Roman Petrenko :: contributions