Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

retrofit dependency in android studio

// Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.6.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.6.0'
    implementation "com.squareup.okhttp3:logging-interceptor:4.5.0"
Comment

retrofit kotlin

//     FULL EXAMPLE FOR RETROFIT 
//add Retrofit dependencies to gradle file
//file build.gradele
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.10'

// create an interface for more flexibility
// file MyAPI.kt
interface MyAPI(){
  
// function calling to server
// @Field("your_name_of_field") under this name we will receive our request on the server
// Like if(isset($_POST("your_name_of_field"))){ do something }  //PHP
  
  @FormUrlEncoded  // required annotation
  @POST("server.php")   // address of the page to which we send data and from which we receive a response
  fun SendAndGetPost(
    @Field("name") userName: String?  
    @Field("password") userPass: String?
  ):Call<ResponsedData?>?  // class ResponsedData.kt 
  

  companion object{
	private val client = OkHttpClient.Builder().build()
		operator fun invoke():MyAPI{
			return Retrofit.Builder()
            	// https://google.com/folder/ (path example)
            	.baseUrl("https://yor_server_path/")
            	.addConverterFactory(GsonConverterFactory.create())
            	.client(client)
            	.build()
            	.create(MyAPI::class.java)
	}
  }
}


// create a class to receive our response from the server
// file ResponsedData.kt
class ResponsedData{
	val email: String? = null
	val age: String? = null
  //variable names must match the names sent from the server !
}


// ActivityMain calls the function and get the data

class ActivityMain : AppCompatActivity(){

	override fun onCreate(savedInstance: Bundle){
		super.onCreate(savedInstance)
        setContentView(R.layout.activity_main)
        
        val name = "myName"
      	val password = "1234567"
        MyAPI().SendAndGetPost(name, password)?enqueue(
        	object: CalBack<ResponsedData?>{
        
              override fun onResponse(
                call: Call<ResponsedData?>,
                response: Response<ResponsedData?>)
              		{
                      if(!response.isSuccessful){
                      	Log.e("API-ERROR", response.code().toString())
                      	return
                      }else{
                        // val answer: ResponsedData
                      	val answer = response.body()
                        email.name
                        age.password
                       // data for use 
                      }
              		}
              override fun onFalure(
                call: Call<ResponsedData?>,
                  t: Throwable)
              {
              	Log.e("API-ERROR", t.printStackTrace())
              }
        	})        
	}

}

--------------------- SERVER SIDE -------------------------------------------
// this is how the file on the server looks like 
// the path to which we registered in the interface of our application
// file server.php
<?php
// Data Base includes
// or any sources 

if(isset($_POST("name")) && isset($_POST("password"))){
  	$js = array(
			'email'=>"some data from DB",
			'age'=>"some data from DB"
			);
  
	echo json_encode($js);
	exit();
}

// all examples are taken from here
// https://square.github.io/retrofit/
Comment

kotlin retrofit2 dependency

implementation 'com.squareup.retrofit2:retrofit:2.6.0'
Comment

kotlin and retrofit

- intoduction
        1. post is used to send data to server

- exapmle
   "simple post"
            @POST("posts")
            Call<Post> createPost(@Body Post post);

   "post with from url encoded "
            @FormUrlEncoded
            @POST("posts")
            Call<Post> createPost( @Field("userId") int userid ,
                                    @Field("title") String title,
                                    @Field("body") String body );

    "using map"
            @FormUrlEncoded
            @POST("posts")
            Call<Post> createPost(@FieldMap Map<String,String> postMap);







- INTERFACE
        public interface MyWebService {

            String BASE_URL = "https://jsonplaceholder.typicode.com/";
            String FEED = "posts";
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        
            @GET(FEED)
            Call<List<Post>> getPosts();
        
        
        }



        
- MODEL CLASS
       public class Post {

            private int userId;
            private int id;
            private String title;
            private String body;
        
            public int getUserId() {
                return userId;
            }
        
            public void setUserId(int userId) {
                this.userId = userId;
            }
        
            public int getId() {
                return id;
            }
        
            public void setId(int id) {
                this.id = id;
            }
        
            public String getTitle() {
                return title;
            }
        
            public void setTitle(String title) {
                this.title = title;
            }
        
            public String getBody() {
                return body;
            }
        
            public void setBody(String body) {
                this.body = body;
            }
        
       }
        
        
        


- IN ACTIVITY WHERE TO SEND POST REQUEST
        Post post = new Post(1,"Post Title","this is post body");

        Map<String,String> postmap = new HashMap<>();
        postmap.put("userId","33");
        postmap.put("title","My post title");
        postmap.put("body","this is my post body in the map");
    
        Call<Post> postCall = myWebService.createPost(postmap);
        postCall.enqueue(new Callback<Post>() {
            @Override
            public void onResponse(Call<Post> call, Response<Post> response) {
                if (response.isSuccessful()){
                    textView.setText(String.valueOf(response.code()));
                    show(response.body());
                }
            }
    
            @Override
            public void onFailure(Call<Post> call, Throwable t) {
    
            }
        });
Comment

PREVIOUS NEXT
Code Example
Java :: How to create an adjacency list representation of a graph, in Java? 
Java :: how to sort a list of integers in java 
Java :: java random seed 
Java :: dupplicate classes android 
Java :: android studio close app 
Java :: print line in jjava 
Java :: find object with same attribute java stream 
Java :: java get unique elements from array 
Java :: array to array list 
Java :: static and final in java 
Java :: ++i vs i++ java 
Java :: difference between java and javax 
Java :: java write 
Java :: printing in java 
Java :: java get random char 
Java :: java alert box 
Java :: print two dimensional array java 
Java :: java filedialog 
Java :: spigot how to kill player 
Java :: java resource file 
Java :: check if all values are same in list java 
Java :: event api spigot 
Java :: copy arraylist java 
Java :: get first letter of string in array java 
Java :: what it means when create final variable in java 
Java :: open gallery android 
Java :: java jframe actionlistener 
Java :: share intent android 
Java :: find minimum number in array java 
Java :: support different screen sizes android 
ADD CONTENT
Topic
Content
Source link
Name
8+9 =