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

PREVIOUS NEXT
Code Example
Java :: how to change double to int in java 
Java :: intellij 
Java :: get minimum of array java 
Java :: java get relative path 
Java :: java string array initialization 
Java :: how to return array in java 
Java :: java print pdf to printer 
Java :: formatting an integer in java 
Java :: how to check base64 in java 
Java :: java math power 
Java :: jbutton open jframe java 
Java :: sum of array elements java 
Java :: android studio download 
Java :: difference between object and class 
Java :: java running sum of array 
Java :: how to operate on values from different classes in java 
Java :: start async task android 
Java :: big java 2010 heaptree java program 
Java :: java create new object 
Java :: how to find prime numbers in java 
Java :: get all keys from pbject javascirpt 
Java :: java print stack 
Java :: java toggle button get state 
Java :: Java heap retention in BodyContentImpl 
Java :: java decompiler 
Java :: java read integer from text file into array scanner 
Java :: how to create a gui in java 
Java :: java types of list 
Java :: java explicit array declaration 
Java :: Java printf() Method 
ADD CONTENT
Topic
Content
Source link
Name
8+4 =