这是我第一次使用改装,我迷失了说明。我阅读了官方指南和其他一些答案和教程,但我仍然遇到麻烦。看起来它们都涵盖了复杂的场景,但不仅仅是一个领域的简单帖子。
这是我想要做的细节。将名称发布到php服务器:
输入:application / x-www-form-urlencoded 有效负载名称:例如名称=约翰%20Smith
我花了很多时间并且有基本的但我认为我错过了一些东西:
我已经知道我需要这样的界面:
public interface ApiService {
@FormUrlEncoded
@POST("./")
Call<User> updateUser(@Field("Name") String name);
}
然后我为我的用户提供了一个模型:
public class User {
@SerializedName("Name")
String name;
}
然后我有我的改装客户:
公共类RetroClient {
private static final String ROOT_URL = "http://alarm.abc.ch/";
public static ApiService RETROFIT_CLIENT;
public static ApiService getInstance() {
//if REST_CLIENT is null then set-up again.
if (RETROFIT_CLIENT == null) {
setupRestClient();
}
return RETROFIT_CLIENT;
}
private static void setupRestClient() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RETROFIT_CLIENT = retrofit.create(ApiService.class);
}
}
我在我的主要活动的post函数中这样称呼它:
public void post (){
mRetrofitCommonService = RetroClient.getInstance();
call = mRetrofitCommonService.updateUser("test");
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
System.out.println("responseee " + response);
}
@Override
public void onFailure(Call<User> call, Throwable t) {
System.out.println("eeee " + t);
}
});
从那里我完全迷失了。我确信这是我想念的小东西,但不确定是什么。
提前感谢您的帮助。
编辑:代码已更改以反映我当前的尝试。这给了我以下错误:
MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 2 path
答案 0 :(得分:2)
你快到了!现在你必须打电话给你的api。
示例代码
public class App {
private ApiService apiService = RetroClient.getApiservice();
public static void main(String[] args) {
User user = new User("username")
Call<User> call = apiService.updateUser(user);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
int statusCode = response.code();
User user = response.body();
// process success
}
@Override
public void onFailure(Call<User> call, Throwable t) {
// process failure
}
});
}
}
使用主要活动的post()方法进行更新
public void post() {
Call<User> call = apiService.updateUser("username");
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
int statusCode = response.code();
User user = response.body();
}
@Override
public void onFailure(Call<User> call, Throwable t) {
// Log error here since request failed
}
});
}
答案 1 :(得分:1)
在getApiService()
返回的对象上,您可以致电updateUser()
。
在回复此调用后,您将收到如下所示的Call
对象:
Call<User> userUpdateCall = RetroClient.getApiService().updateUser(somestring);
然后同步执行此调用请执行以下操作:
userUpdateCall.execute();
<强>更新强>
抱歉,我以前错过了。在ApiService
界面中,执行以下操作:
@FormUrlEncoded
@POST("YourPostEndpoint")
Call<User> updateUser(@Field("Name") String name);
ASYNC CALL
有关详细信息,请参阅here
要异步调用它,而不是.execute()
使用以下代码(从上面链接获取的代码并修改为此方案:
userUpdateCall.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
// user available
} else {
// error response, no access to resource?
}
}
@Override
public void onFailure(Call<List<Task>> call, Throwable t) {
Log.d("Error", t.getMessage());
}
}
答案 2 :(得分:1)
请参阅我的onCreate方法我是如何做到的。
public class LoginActivity extends AppCompatActivity {
RetrofitCommonService mRetrofitCommonService;
Call<LoginResponse> call;
String firstName, lastName, userId, token;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mRetrofitCommonService = RetrofitClient.getInstance();
call = mRetrofitCommonService.doLogin("danish.sharma@gmail.com", "12345678");
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LoginData responseReg = response.body().getData();
firstName = responseReg.getFirstName();
lastName = responseReg.getLastName();
userId = responseReg.getUserId();
token = responseReg.getToken();
System.out.println("responseee " + firstName + " " + lastName);
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
System.out.println("eeee " + t);
}
});
}
}
我的RetrofitClient类:
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Danish.sharma on 7/22/2016.
*/
public class RetrofitClient {
public static final String BASE_URL = "http://face2friend.com/";
public static RetrofitCommonService RETROFIT_CLIENT;
public static RetrofitCommonService getInstance() {
//if REST_CLIENT is null then set-up again.
if (RETROFIT_CLIENT == null) {
setupRestClient();
}
return RETROFIT_CLIENT;
}
private static void setupRestClient() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RETROFIT_CLIENT = retrofit.create(RetrofitCommonService.class);
}
}
&安培; RetrofitCommonService类:
import com.aquasoft.retrofitexample.model.LoginResponse;
import com.aquasoft.retrofitexample.model.RegistrationResponse;
import com.aquasoft.retrofitexample.model.UserImageResponse;
import com.aquasoft.retrofitexample.model.VehicleResponse;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
/**
* Created by Danish.sharma on 7/22/2016.
*/
public interface RetrofitCommonService {
/*@POST("http://server.pogogamessupport.com/parkway/api/v1/registration")
Call<RegistrationResponse> createUser(@Body RegistrationResponse user);*/
@FormUrlEncoded
@POST("registration")
Call<RegistrationResponse> doRegistration(@Field("email") String email, @Field("firstname") String firstname, @Field("lastname")
String lastname, @Field("password") String password);
@FormUrlEncoded
@POST("login")
Call<LoginResponse> doLogin(@Field("email") String email, @Field("password") String password);
@FormUrlEncoded
@POST("listvehicle")
Call<VehicleResponse> getAllVehicle(@Field("userId") String userId, @Field("token") String token);
@Multipart
@POST("updateprofilepic")
Call<UserImageResponse> updateUserImage(@Part("userId") RequestBody userId, @Part("token") RequestBody token, @Part MultipartBody.Part image);
}
&安培;关于build.gradle中依赖项的最后一件事,我正在使用:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'
provided 'org.glassfish:javax.annotation:10.0-b28'
}
如果您仍需要任何帮助,请发表评论。