Make an HTTP request with android

后端 未结 12 1086
时光取名叫无心
时光取名叫无心 2020-11-21 06:38

I have searched everywhere but I couldn\'t find my answer, is there a way to make a simple HTTP request? I want to request a PHP page / script on one of my websites but I do

12条回答
  •  感情败类
    2020-11-21 07:03

    For me, the easiest way is using library called Retrofit2

    We just need to create an Interface that contain our request method, parameters, and also we can make custom header for each request :

        public interface MyService {
    
          @GET("users/{user}/repos")
          Call> listRepos(@Path("user") String user);
    
          @GET("user")
          Call getUserDetails(@Header("Authorization") String   credentials);
    
          @POST("users/new")
          Call createUser(@Body User user);
    
          @FormUrlEncoded
          @POST("user/edit")
          Call updateUser(@Field("first_name") String first, 
                                @Field("last_name") String last);
    
          @Multipart
          @PUT("user/photo")
          Call updateUser(@Part("photo") RequestBody photo, 
                                @Part("description") RequestBody description);
    
          @Headers({
            "Accept: application/vnd.github.v3.full+json",
            "User-Agent: Retrofit-Sample-App"
          })
          @GET("users/{username}")
          Call getUser(@Path("username") String username);    
    
        }
    

    And the best is, we can do it asynchronously easily using enqueue method

提交回复
热议问题