Klien .NET Restful Http yang kuat, mendukung pencegat, konversi pesan, Dapatkan, Posting, Masukkan, Hapus, unggah file, unduh file, Proxy, verifikasi sertifikat Https
Kerangka Sasaran | Versi | Ya / Tidak |
---|---|---|
.BERSIH | 8.x | Ya |
.BERSIH | 7.x | Ya |
.BERSIH | 6.x | Ya |
.BERSIH | 5.x | TIDAK |
.NET Inti | 3.x | TIDAK |
.NET Inti | 2.x | TIDAK |
Standar .NET | 2.1 | TIDAK |
Standar .NET | 2.0 | TIDAK |
Standar .NET | 1.x | TIDAK |
.NET Kerangka | Semua | TIDAK |
dotnet add package RetrofitNet
public interface IPersonService
{
[ HttpPost ( "/api/Auth/GetJwtToken" ) ]
Response < TokenModel > GetJwtToken ( [ FromForm ] AuthModel auth ) ;
[ HttpGet ( "/api/Person" ) ]
Response < IList < Person > > Get ( ) ;
[ HttpPost ( "/api/Person" ) ]
Response < Person > Add ( [ FromBody ] Person person ) ;
[ HttpGet ( "/api/Person/{id}" ) ]
Response < Person > Get ( [ FromPath ] int id ) ;
[ HttpPut ( "/api/Person/{id}" ) ]
Response < Person > Update ( [ FromPath ] int id , [ FromBody ] Person person ) ;
[ HttpDelete ( "/api/Person/{id}" ) ]
Response < Person > Delete ( [ FromPath ] int id ) ;
[ HttpGet ( "https://www.baidu.com/index.html" ) ]
Response < dynamic > GetBaiduHome ( ) ;
}
using Retrofit . Net . Core ;
using Retrofit . Net . Core . Models ;
var client = new RetrofitClient . Builder ( )
. AddInterceptor ( new HeaderInterceptor ( ) )
. Build ( ) ;
var retrofit = new Retrofit . Net . Core . Retrofit . Builder ( )
. AddBaseUrl ( "https://localhost:7177" )
. AddClient ( client )
. Build ( ) ;
var service = retrofit . Create < IPersonService > ( ) ;
Response < TokenModel > authResponse = service . GetJwtToken ( new AuthModel ( ) { Account = "admin" , Password = "admin" } ) ;
Response < IList < Person > > response = await service . Get ( ) ;
Console . WriteLine ( JsonConvert . SerializeObject ( response ) ) ;
Response < Person > response = await service . Add ( new Person { Id = 1 , Name = "老中医" , Age = 18 } ) ;
Console . WriteLine ( JsonConvert . SerializeObject ( response ) ) ;
var response = service . Update ( 1 , new Person ( ) { Name = "Charlie" } ) ;
var response = service . Delete ( 1 ) ;
KirimEntity.cs
public class SubmitEntity
{
public string Name { get ; set ; }
public FieldFile File { get ; set ; }
// You can upload multiple files including parameters like this
// public FieldFile File2 { get; set; }
// for more File3,File4...
}
mengunggah
var response = service . Submit ( new SubmitEntity {
Name = "老中医" ,
File = new FieldFile { FilePath = "/Users/onllyarchibald/Downloads/icon_unlocked.png" }
} ) ;
Console . WriteLine ( JsonConvert . SerializeObject ( response ) ) ;
…Anda dapat menemukan lebih banyak contoh kode di sini.
Tentukan api Anda:
[ HttpGetStream ( "/WeatherForecast/Download" ) ]
Task < Response < Stream > > Download ( [ FromQuery ] string arg1 ) ;
Contoh:
Response < Stream > response = await service . Download ( "test" ) ;
Setelah mendapatkan aliran reaktif http, Anda dapat menyimpannya, seperti ini:
Response < Stream > response = await service . Download ( "test" ) ;
Stream outStream = File . Create ( "/Users/onllyarchibald/Desktop/a.zip" ) ;
byte [ ] buffer = new byte [ 1024 ] ;
int i ;
do {
i = response . Body ! . Read ( buffer , 0 , buffer . Length ) ;
if ( i > 0 ) outStream . Write ( buffer , 0 , i ) ;
} while ( i > 0 ) ;
outStream . Close ( ) ;
response . Body . Close ( ) ;
Console . WriteLine ( "File download completed..." ) ;
Tangkapan layar di bawah menggunakan plugin ShellProgressBar. Silakan lihat kode untuk detailnya. …Anda dapat menemukan lebih banyak contoh kode di sini.
application / json - > [ FromBody ]
multipart / form - data - > [ FromForm ]
Di sini Anda dapat mengonfigurasi konverter 'interceptor', 'timeout', 'response'. seperti ini:
var client = new RetrofitClient . Builder ( )
. AddInterceptor ( new HeaderInterceptor ( ) ) // Add Interceptor
. AddInterceptor ( new SimpleInterceptorDemo ( ) ) // ...
. AddTimeout ( TimeSpan . FromSeconds ( 10 ) ) // The default wait time after making an http request is 6 seconds
. Build ( ) ;
var retrofit = new Retrofit . Net . Core . Retrofit . Builder ( )
. AddBaseUrl ( "https://localhost:7283" ) // Base Url
. AddClient ( client )
. AddConverter ( new DefaultXmlConverter ( ) ) // The internal default is ‘DefaultJsonConverter’ if you don’t call ‘.AddConverter(new DefaultJsonConverter())’
. Build ( ) ;
Anda dapat menemukan lebih banyak contoh kode di sini.
Respons atas permintaan berisi informasi berikut.
public class Response < T >
{
// Http message
public string ? Message { get ; internal set ; }
// Response body. may have been transformed, please refer to Retrofit.Builder.AddConverterFactory(...).
public T ? Body { get ; internal set ; }
// Http status code.
public int StatusCode { get ; internal set ; }
// Response headers.
public IEnumerable < KeyValuePair < string , object > > ? Headers { get ; internal set ; }
}
Ketika permintaan berhasil, Anda akan menerima respons sebagai berikut:
Response < IList < Person > > response = await service . Get ( ) ;
Console . WriteLine ( response . Body ) ;
Console . WriteLine ( response . Message ) ;
Console . WriteLine ( response . StatusCode ) ;
Console . WriteLine ( response . Headers ) ;
Untuk setiap permintaan http, kita dapat menambahkan satu atau lebih pencegat, yang dengannya kita dapat mencegat permintaan, respons, dan kesalahan.
.. . RetrofitClient . Builder ( )
. AddInterceptor ( new YourCustomInterceptor ( ) )
. Build ( ) ;
public class SimpleInterceptorDemo : ISimpleInterceptor
{
public void OnRequest ( Request request )
{
Debug . WriteLine ( $ "REQUEST[ { request . Method } ] => PATH: { request . Path } " ) ;
}
public void OnResponse ( Response < dynamic > response )
{
Debug . WriteLine ( $ "RESPONSE[ { response . StatusCode } ] => Message: { response . Message } " ) ;
}
}
Pencegat tingkat lanjut dapat diimplementasikan dengan mewarisi antarmuka IAdvancedInterceptor. Kemudian saya akan memberitahu Anda melalui contoh pembaruan token
public class HeaderInterceptor : IAdvancedInterceptor
{
public Response < dynamic > Intercept ( IChain chain )
{
// Get token from local file system
string ? token = null ;
if ( File . Exists ( "token.txt" ) ) token = File . ReadAllText ( "token.txt" ) ;
// Add token above
Request request = chain . Request ( ) . NewBuilder ( )
. AddHeader ( "Authorization" , $ "Bearer { token } " )
. Build ( ) ;
Response < dynamic > response = chain . Proceed ( request ) ;
if ( response . StatusCode == 401 )
{
// Get a new token and return
// The way to get the new token here depends on you,
// you can ask the backend to write an API to refresh the token
request = chain . Request ( ) . NewBuilder ( )
. AddHeader ( "Authorization" , $ "Bearer <new token>" )
. Build ( ) ;
// relaunch!
response = chain . Proceed ( request ) ;
}
return response ;
}
}
Di semua pencegat, Anda dapat mengganggu alur eksekusinya. Jika Anda ingin menyelesaikan permintaan/respons dengan beberapa data khusus, Anda dapat memanggil return new Response<dynamic>();
.
public Response < dynamic > Intercept ( IChain chain )
{
return new Response < dynamic > ( ) ;
}
Converter
memungkinkan data permintaan/respons diubah sebelum dikirim/diterima ke server. Saya telah menerapkan DefaultXmlConverter
dan DefaultJsonConverter
sebagai konverter default. Jika Anda ingin menyesuaikan konversi data permintaan/respons, Anda dapat menentukan kelas yang mewarisi 'IConverter' dan mengganti DefaultJsonConverter
dengan menyetel .AddConverter(new YourCustomConverter())
.
public class DefaultJsonConverter : IConverter
{
// value: Data returned from the server
// type: The return type of the interface you declared
// return value: What type do you want to convert to? Here is to convert the json returned by the server /// to the interface return type you defined
public object ? OnConvert ( string from , Type to )
{
if ( from is null ) return from ;
if ( to == typeof ( Stream ) ) return from ;
if ( to ? . Namespace ? . StartsWith ( "System" ) is not true )
{
return JsonConvert . DeserializeObject ( from . ToString ( ) ?? "" , to ! ) ;
}
return from ;
}
}
Anda dapat menemukan lebih banyak contoh kode di sini.
Proyek sumber terbuka ini disahkan oleh https://github.com, dan lisensinya adalah MIT.
Silakan ajukan permintaan fitur dan bug di pelacak masalah.