一个简单的便利库,用于使用 HttpURLConnection 发出请求并访问响应。
该库可根据 MIT 许可证使用。
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 请求的行为添加便利性和通用模式,例如用于构建请求的流体接口以及对多部分请求等功能的支持。
底线:该库的唯一目标是提高HttpURLConnection
类的可用性。
没有任何。该库的目标是成为具有一些内部静态类的单个类。该测试项目确实需要 Jetty 来测试针对实际 HTTP 服务器实现的请求。
HttpRequest
类不会抛出任何已检查的异常,而是所有低级异常都包含在扩展RuntimeException
的HttpRequestException
中。您可以通过捕获HttpRequestException
并调用getCause()
来访问底层异常,该方法将始终返回原始IOException
。
不。每个HttpRequest
对象包装的底层HttpUrlConnection
对象都有一个同步 API,因此HttpRequest
上的所有方法也是同步的。
因此,不要在应用程序的主线程上使用HttpRequest
对象,这一点很重要。
下面是一个从 AsyncTask 使用它的简单 Android 示例:
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=100
int [] 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[]=23
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 ();
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 ();
希望将此库与 OkHttp 一起使用?在这里阅读。
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 );
}
});