简体   繁体   中英

How to call php using retrofit in android?

To call php (post) from android app using Retrofit .

i get response from php in onResponse as success, but unable to receive json parameter.

Php url :
     http://www.example.com/projectname/login.php 
Parameter :
username = "mumbai"
password = "mumbai"

MainActivity.java

ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
        Call sosSensCall = apiService.getLogin("mumbai", "mumbai");
        sosSensCall.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Example example = (Example) response.body();
                Log.d("sk_log","==="+example.getUserId());   
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                Log.d("sk_log", "Failed! Error = " + t.getMessage());
            }
});

APIClient.java

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class ApiClient {

    public static final String BASE_URL = "http://www.example.com/";
    private static Retrofit retrofit = null;
    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();           
        }
        return retrofit;
    }
}

ApiInterface.java

public interface ApiInterface {
   @POST("projectname/login.php")
Call<Example> getLogin(@Query("username") String username, @Query("password") String password);
}

I got the bug solved : The error was in ApiInterface.java, have changed '@Query' to '@Field'

Modified ApiInterface.java

public interface ApiInterface {
   @POST("projectname/login.php")
Call<Example> getLogin(@Field("username") String username, @Field("password") String password);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM