一個簡單的便利庫,用於使用 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 );
}
});