retrofit do conteúdo notas

 

O problema?

princípio 6.retrofit: Modo Proxy Dinâmico
uso básico do 5.retrofit?
4. O uso de projetos de modernização (processos básicos e registros de upload de arquivos e imagens)? Especial: arquivo (e fotos) para carregar
o significado eo papel da 3.Retrofit várias anotações?
Métodos 2.android pedido retrofit formato parâmetro RequestBody de
modelo 1.retrofit?

 

====  

5.retrofit uso básico:


MovieService interface pública {
@GET ( "top250")
Chamar <MovieEntity> getTopMovie (@query ( "start") int começar, @ consulta ( "contagem") int count);
}
然后你还需要创建一个Retrofit对象:
public static final de Cordas baseUrl = "https://api.douban.com/v2/movie/";
Retroajuste retroajuste = novo Retrofit.Builder ()
.baseUrl (baseUrl)
.addConverterFactory (GsonConverterFactory.create ())
.build ();

O objeto é, então, para criar uma MovieService Retrofit objetos:
MovieService movieService = retrofit.create (MovieService.class);
Chamar <MovieEntity> Chamada movieService.getTopMovie = (0,10);
//call.enqueue () pedido assíncrono, call.execute () pedido de sincronização
call.enqueue (o Callback nova novo <MovieEntity> () {
@Override
public void onResponse (Chamada <MovieEntity> Chamada, a resposta <MovieEntity> Response) {
result_TV.setText (response.body () toString ()) .;
}
@Override
vazio do onFailure (Chamada <MovieEntity> Chamada, o Throwable T) {public
result_TV.setText (t.getMessage ());
}
});
aqui também pode remover um pedido:
Retrofit não cancelada diretamente versão 1.x razões metodológicas tarefa contínua na versão 2.x, modo de serviço se torna a forma da chamada é para fazer transações em curso pode ser cancelado.
Para fazer isso, basta ligar para call.cancel ().
Estes são os Retrofit2.0 uso básico do seguinte palestra detalhada sobre o seu uso:


o uso de retrofit 4. projeto (o processo e upload de arquivos de registros e imagens básicas)?

4.1项目中retrofit的使用流程:
interface pública CommonApi {
@POST ( "common / getTime.htm")
Observable <BaseJson <Longo >> getNetTime (@Body RequestBody requestBody);
}

Public class UsualConfigModel estende implementos BaseModel UsualConfigContract.Model {
@Override
pública Observable <BaseJson <Longo >> getNetTime (Map <String, Object> HashMap) {
Observable <BaseJson <Longo >> observável = mRepositoryManager.obtainRetrofitService (CommonApi.class)
. getNetTime (ToRequestBodyUtil.toRequestBody (hashmap));
voltar observável;
}
}

public static RequestBody toRequestBody (Map <String, Object> mapa) {
entrada String = buildParams (mapa);
de entrada = replaceURL (de entrada);
// RequestBody requestBody = RequestBody.create (MediaType.parse ( "application / json, text / plain; charset = utf-8"), de entrada);
RequestBody requestBody = RequestBody.create (MediaType.parse ( "application / x-www-forma-urlencoded; charset = utf-8"), de entrada);
voltar requestBody;
}

public static RequestBody buildParamV2 (Map <String, String> paramsMap, boolean isFilter) {
FormBody.Builder builder = new FormBody.Builder ();
para (String chave: paramsMap.keySet ()) {
Cadeia valor = paramsMap.get (chave);
builder.add (chave, valor); //追加表单信息
}
RequestBody formBody = builder.build ();
// pedido Pedido = new Request.Builder () url (netUrl) .post (formBody) .build (.);
voltar formBody;
}

arquivos 4.2 retrofit do projeto (e imagens) enviados utilizando o processo:
classe VisitApi:
/ **
* @des: detalhes da conferência - novos: arquivos de arquivos, envio de fotos, etc .: ( "", param, arquivos ) .then (());
// desta maneira:
* /
@POST ( "Record / Reunião / saveRecordMeetingInfo.htm")
Observable <MeetDetail> newAddMeetDetail (@Body corpo requestBody);

@Multipart
@POST ( "Record / Reunião / saveRecordMeetingInfo .htm ")
Observable <BaseCode> newAddMeetDetailV1 (@QueryMap o Map <string, Object> usermaps, Lista @Part <MultipartBody.Part> filemap,
Lista @Part <MultipartBody.Part> PhotoMap, Lista @Part <MultipartBody.Part> signMap) ;

@Multipart
@POST ( "record / reunião / saveRecordMeetingInfo.htm")
observáveis <BaseCode> newAddMeetDetailV2 (@QueryMap Map <String, Object> usermaps, @PartMap Map <String, RequestBody> filemap,
@PartMap Map <String, RequestBody> PhotoMap , @PartMap Map <string, RequestBody> signMap);

/ **
* @des:会议修改的接口
* /
@Override
pública Observable <MeetDetail> changedMeetDetail (Map <String, Object> HashMap, List <string> filepaths, List <string> photoPaths, List <string> signPaths) {
MultipartBody .Builder compilação = novo MultipartBody.Builder ();
for (Map.Entry <String, Object> entrada: hashMap.entrySet ()) {
string key = entry.getKey ();
Valor objeto = entry.getValue ();
build.addFormDataPart (key, String.valueOf (valor)); //
}
if (! filepaths = null && filePaths.size ()> 0) {
for (int i = 0; i <filePaths.size (); i ++) {
arquivo file = new File (filePaths.get (i));
RequestBody fileRQ = RequestBody.create (MediaType.parse ( "form-várias vias / dados"), arquivo);
build.addFormDataPart ( "arquivos", file.getName (), fileRQ); //
}
}
if (! photoPaths = null && photoPaths.size ()> 0) {
for (int i = 0; i <photoPaths.size ( ); i ++) {
arquivo File = new File (photoPaths.get (i));
RequestBody fileRQ = RequestBody.create (MediaType.parse ( "image / *"), arquivo);
build.addFormDataPart ( "fotos", file.getName (), fileRQ);


MultipartBody corpo build.build = (); // MultipartBody继承RequestBody
Observable <MeetDetail> observável = mRepositoryManager.obtainRetrofitService (VisitApi.class)
.changedMeetDetail (corpo);
voltar observável;
}

//不适合的方法:
públicas observáveis <BaseCode> changedMeetDetail2 (Map <String, Object> HashMap, List <string> filepaths, List <string> photoPaths, List <string> signPaths) {
List <MultipartBody.Part> parts1 = new ArrayList <> ();
if (! filepaths = null && filePaths.size ()> 0) {
for (int i = 0; i <filePaths.size (); i ++) {
arquivo File = new File (filePaths.get (i));
RequestBody fileRQ = RequestBody.create (MediaType.parse ( "form-várias vias / dados"), arquivo);
MultipartBody.Part parte = MultipartBody.Part.createFormData ( "arquivos", file.getName (), fileRQ);
parts1.add (parte);
}
} Else {
MultipartBody.Part parte = MultipartBody.Part.createFormData ( "", "");

List <MultipartBody.Part> parts2 = new ArrayList <> ();
if (! photoPaths = null && photoPaths.size ()> 0) {
for (int i = 0; i <photoPaths.size (); i ++) {
arquivo File = new File (photoPaths.get (i));
RequestBody fileRQ = RequestBody.create (MediaType.parse ( "image / *"), arquivo);
MultipartBody.Part parte = MultipartBody.Part.createFormData ( "fotos", file.getName (), fileRQ);
parts2.add (parte);
}
} Else {
MultipartBody.Part parte = MultipartBody.Part.createFormData ( "", ""); //直接传入两个空字符串就可以了...不能传null;
parts2.add (parte);
}
Observable <BaseCode> observável = null;
// Observable <BaseCode> observável = mRepositoryManager.obtainRetrofitService (VisitApi.
// .changedMeetDetail (hashmap, parts1, parts2, parts3);
voltar observável;
}

Acho que você gosta

Origin www.cnblogs.com/awkflf11/p/12541221.html
Recomendado
Clasificación