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 android

def retrofit_version = "2.9.0"
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
Comment

retrofit implementation

dependencies {
    implementation "com.google.code.gson:gson:2.8.7"
    implementation "com.squareup.retrofit2:retrofit:2.9.0"
    implementation "com.squareup.retrofit2:converter-gson:2.9.0"

}
Comment

retrofit android

implementation 'com.squareup.retrofit2:retrofit:2.9.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

retrofit

public interface MyApiEndpointInterface {
    // Request method and URL specified in the annotation
    // Callback for the parsed response is the last parameter

    @GET("users/{username}")
    void getUser(@Path("username") String username, Callback<User> cb);

    @GET("group/{id}/users")
    void groupList(@Path("id") int groupId, @Query("sort") String sort, Callback<List<User>> cb);

    @POST("users/new")
    void createUser(@Body User user, Callback<User> cb);
}
Comment

retrofit

dependencies {
    implementation 'com.google.code.gson:gson:2.8.7'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'  

}
Comment

retrofit android

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}
Comment

retrofit

Gson gson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
        .create();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build();
Comment

retrofit

RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("title", "Square Logo")
        .addFormDataPart("image", "logo-square.png",
            RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
        .build();
Comment

retrofit

// Trailing slash is needed
public static final String BASE_URL = "http://api.myservice.com/";
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();
Comment

retrofit

User user = new User(123, "John Doe");
Call<User> call = apiService.createuser(user);
call.enqueue(new Callback<User>() {
  @Override
  public void onResponse(Call<User> call, Response<User> response) {

  }

  @Override
  public void onFailure(Call<User> call, Throwable t) {

  }
Comment

Retrofit interface

package com.vogella.java.retrofitgerrit;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface GerritAPI {

    @GET("changes/")
    Call<List<Change>> loadChanges(@Query("q") String status);
}
Comment

Retrofit

// retrofit
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

// Junit
testImplementation("org.junit.jupiter:junit-jupiter-api:5.0.0")
testRuntime("org.junit.jupiter:junit-jupiter-engine:5.0.0")
// to run JUnit 3/4 tests:
testImplementation("junit:junit:4.12")
testRuntime("org.junit.vintage:junit-vintage-engine:4.12.0")
Comment

retrofit

public interface MyApiEndpointInterface {
    // Request method and URL specified in the annotation

    @GET("users/{username}")
    Call<User> getUser(@Path("username") String username);

    @GET("group/{id}/users")
    Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

    @POST("users/new")
    Call<User> createUser(@Body User user);
}
Comment

retrofit

@Multipart
@POST("some/endpoint")
Call<Response> uploadImage(@Part("description") String description, @Part("image") RequestBody image)
Comment

Get Method Retrofit

 public interface IService {

      String BASE_URL = "https://api.test.com/";
      String API_KEY = "SFSDF24242353434";

      @GET("Search") //i.e https://api.test.com/Search?
      Call<Products> getProducts(@Query("one") String one, @Query("two") String two,    
                                @Query("key") String key)
}
Comment

PREVIOUS NEXT
Code Example
Java :: base64 in java 
Java :: Islands count leetcode 
Java :: odd number in java 
Java :: get driver mysql 
Java :: Java make digit numbers 
Java :: check self permission android write_external_storage 
Java :: java remove duplicates 
Java :: how to iterate pixels image java 
Java :: find min in array java 
Java :: java get all directories in path 
Java :: android recyclerview item click listener 
Java :: UTC in Java 
Java :: set size button java 
Java :: running sum of 1d array java 
Java :: responseentity spring boot 
Java :: spring.jpa.properties.hibernate 
Java :: Java Create a ConcurrentHashMap 
Java :: arrays in java 
Java :: java loop through list 
Java :: sort an int array java 
Java :: android separator line in view 
Java :: java replace a character at end of string 
Java :: retrofit android 
Java :: how to return array in java 
Java :: how to check base64 in java 
Java :: java string to uuid 
Java :: java.lang.string cannot be cast to java.lang.double react native 
Java :: java sort int array 
Java :: start async task android 
Java :: java using .indexof to fin a space 
ADD CONTENT
Topic
Content
Source link
Name
5+4 =