عميل .NET Restful Http قوي، يدعم الاعتراض، تحويل الرسائل، الحصول على، نشر، وضع، حذف، تحميل الملفات، تنزيل الملفات، الوكيل، التحقق من شهادة Https
الإطار المستهدف | إصدار | نعم/لا |
---|---|---|
.شبكة | 8.x | نعم |
.شبكة | 7.x | نعم |
.شبكة | 6.x | نعم |
.شبكة | 5.x | لا |
صافي النواة | 3.x | لا |
صافي النواة | 2.x | لا |
معيار صافي | 2.1 | لا |
معيار صافي | 2.0 | لا |
معيار صافي | 1.x | لا |
صافي الإطار | الجميع | لا |
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 ) ;
SubmitEntity.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...
}
رفع
var response = service . Submit ( new SubmitEntity {
Name = "老中医" ,
File = new FieldFile { FilePath = "/Users/onllyarchibald/Downloads/icon_unlocked.png" }
} ) ;
Console . WriteLine ( JsonConvert . SerializeObject ( response ) ) ;
…يمكنك العثور على المزيد من أمثلة التعليمات البرمجية هنا.
تحديد واجهة برمجة التطبيقات الخاصة بك:
[ HttpGetStream ( "/WeatherForecast/Download" ) ]
Task < Response < Stream > > Download ( [ FromQuery ] string arg1 ) ;
مثال:
Response < Stream > response = await service . Download ( "test" ) ;
بعد الحصول على تدفق http التفاعلي، يمكنك تخزينه، على النحو التالي:
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..." ) ;
تستخدم لقطة الشاشة أدناه البرنامج المساعد ShellProgressBar. يرجى الاطلاع على الرمز للحصول على التفاصيل. …يمكنك العثور على المزيد من أمثلة التعليمات البرمجية هنا.
application / json - > [ FromBody ]
multipart / form - data - > [ FromForm ]
هنا يمكنك تكوين محول "المعترض" و"المهلة" و"الاستجابة". مثله:
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 ( ) ;
يمكنك العثور على مزيد من الأمثلة على التعليمات البرمجية هنا.
تحتوي الاستجابة للطلب على المعلومات التالية.
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 ; }
}
عند نجاح الطلب، سوف تتلقى الرد على النحو التالي:
Response < IList < Person > > response = await service . Get ( ) ;
Console . WriteLine ( response . Body ) ;
Console . WriteLine ( response . Message ) ;
Console . WriteLine ( response . StatusCode ) ;
Console . WriteLine ( response . Headers ) ;
لكل طلب http، يمكننا إضافة واحد أو أكثر من أجهزة الاعتراض، والتي من خلالها يمكننا اعتراض الطلبات والاستجابات والأخطاء.
.. . 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 } " ) ;
}
}
يمكن تنفيذ الاعتراضات المتقدمة عن طريق وراثة واجهة IAdvancedInterceptor. ثم سأخبرك من خلال مثال لتجديد الرمز المميز
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 ;
}
}
في جميع المعترضات، يمكنك التدخل في تدفق تنفيذها. إذا كنت تريد حل الطلب/الاستجابة باستخدام بعض البيانات المخصصة، فيمكنك الاتصال بـ return new Response<dynamic>();
.
public Response < dynamic > Intercept ( IChain chain )
{
return new Response < dynamic > ( ) ;
}
يسمح Converter
بتغيير بيانات الطلب/الاستجابة قبل إرسالها/استلامها إلى الخادم. لقد قمت بتطبيق DefaultXmlConverter
و DefaultJsonConverter
كمحول افتراضي. إذا كنت تريد تخصيص تحويل بيانات الطلب/الاستجابة، فيمكنك تحديد فئة ترث 'IConverter' واستبدال DefaultJsonConverter
عن طريق تعيين .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 ;
}
}
يمكنك العثور على مزيد من الأمثلة على التعليمات البرمجية هنا.
هذا المشروع مفتوح المصدر مرخص من https://github.com، والترخيص من معهد ماساتشوستس للتكنولوجيا.
يرجى تقديم طلبات الميزات والأخطاء في أداة تعقب المشكلات.