Retrofit URL Configuration

Source: Internet
Author: User
Tags http request

Before the beginning of the text, say a toss for 2 days to figure things out.

If you use POST request to submit data (such as user registration, login, etc. form class request), parameter types must be accurate, is field, if you select query, and debugging process did not find this problem, trust me you will go crazy.

@FormUrlEncoded
@POST ("/some/endpoint")
call<response> Register (@Field ("name") String name);

@FormUrlEncoded
@POST ("/some/endpoint")
call<someresponse> someendpoint (@FieldMap map<string, string> names);

@FormUrlEncoded must be brought on to prevent garbled characters from appearing.

Retrofit supports protocols including Get/post/put/delete/head/patch, but you can also customize requests directly with HTTP. These protocols are configured in the form of annotations, such as we have seen the use of Get:

Public interface Ifamousinfo {  

    @GET ("/avatardata/mingrenmingyan/lookup")  
    call<famousinfo> Getfamousresult (@Header ("Apikey") string apikey,  
                                     @Query ("keyword") string keyword,  
                                     @Query ("page") int page,  
                                     @Query ("Rows") int rows);  
  

From: http://blog.csdn.net/jdsjlzx/article/details/51354778

Also like the following:

@GET ("Users/{user}/repos")
  call<list<repo>> Listrepos (@Path ("user") String user);

These annotations have a parameter value that configures their paths, such as the users/{user}/repos in the example, and we note that we also passed a baseurl ("https://api.github.com/") at the time of constructing retrofit. , the full Url of the request is integrated by the BaseURL with the value of the annotation ("path" below), and the rules of the specific integration are as follows:

Path is the form of an absolute path:
Path = "/apath", BaseURL = "http://host:port/a/b"
URL = "Http://host:port/apath"

Path is a relative path, and BaseURL is a directory form:
Path = "Apath", BaseURL = "http://host:port/a/b/"
URL = "Http://host:port/a/b/apath"

Path is a relative path, BaseURL is a file form:
Path = "Apath", BaseURL = "http://host:port/a/b"
URL = "Http://host:port/a/apath"

Path is the complete URL:
Path = "Http://host:port/aa/apath", BaseURL = "http://host:port/a/b"
URL = "Http://host:port/aa/apath"

It is recommended that you configure it in the second way and use the same path as much as possible. If you mix multiple configuration forms in your code, you can get a bunch of bugs in minutes. parameter Type

When you send a request, you need to pass in a parameter that retrofit the parameters of the Http request to become more direct and type-safe in the form of annotations.

Query & QueryMap (GET request)

@GET ("/list")
call<responsebody> list (@Query ("page") int page);

Query is actually the key-value behind the '? ' in the URL, such as:

Http://www.baidu.com/?cate=android

The cate=android here is a Query, and when we configure it we only need to add an argument to the interface method:

Interface printlnserver{    
   @GET ("/")    
   call<string> Cate (@Query ("Cate") String Cate);

If there are a lot of query, so write it is not very tired. And depending on the situation, some fields may not be transmitted, which is clearly inconsistent with the parameter requirements of the method. At this point, the larger capacity of the QueryMap is your best choice.

Field & Fieldmap (POST request)
In fact, we use a relatively large number of POST scenarios, the vast majority of the server interface need to do encryption, authentication and verification, get obviously not very good to meet this demand. The scenario for submitting the form using POST is just what you need and how to do it.

@FormUrlEncoded
   @POST ("/")   
   call<responsebody> Submit (
       @Field ("name") String name,
       @Field (" Occupation ") String occupation);

In fact, it's simple, we just need to define the interface above, we use Field to declare the items of the form, so that submitting the form is as straightforward as a normal function call.

As with query, if you have a lot of field parameters, don't be afraid, just try Fieldmap.

Part & Partmap (POST request)
This is for uploading files. With retrofit, MOM no longer need to worry about file upload trouble ~ ~ ~

Public interface Fileuploadservice {  
    @Multipart
    @POST ("Upload")    
call<responsebody> upload (@Part ( "description") requestbody description,
                              @Part multipartbody.part file);

If you need to upload files, similar to what we have done earlier, define an interface method, and note that this method no longer has @FormUrlEncoded this annotation, but instead of @Multipart, then only need to add part to the parameter. Perhaps you will ask what is the difference between part and Field here, in fact, from a functional point of view, the client initiates requests to carry parameters differently from the server, and the former can carry a richer range of parameter types, including data flow.

It is also because of this that we can upload the file in this way, we will give the interface to use the following method:

During the experiment, I uploaded a file that contained only one line of text:

Visit me:http://www.println.net

So let's go to the service side and see what our request looks like:

HEADERS

Form/post PARAMETERS

Description:this is a description

RAW body

Finally, a trick is released.

Retrofit2 "Multiple query parameters with the same name"

Link below:

Https://api.stay4it.com/tasks?id=123

This API example simply returns the response of id=123 individual tasks.

Public interface Taskservice {
    @GET ("/tasks")
    call<task> Gettask (@Query ("id") long taskId);

So the question is, if you have more than one ID parameter, how do you solve it?

multiple Query Parameters

We need the requested URL just like the following

https://api.stay4it.com/tasks?id=123&id=124&id=125

The response we expect to return is a ids=[123, 124, 125] Query parameter Task List.

Retrofit executes a request containing multiple parameters of the same name by providing a list of IDs as a parameter. Retrofit corresponds to the given list and multiple parameters with the same name.

Public interface Taskservice {
    @GET ("/tasks")
    call<list<task>> Gettask (@Query ("id") list< Long> taskids);
}

@Body

This usage requires the cooperation of the server interface.

@POST ("/users/new")
call<user> createuser (@Body user user);
}

Add:
http://blog.csdn.net/jdsjlzx/article/details/51607867

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.