来自我服务器的Json响应将是这样的:
{"loginResult":"{\"Result\":2,\"UserID\":0,\"ModuleID\":1,\"ModuleName\":\"CRM\"}"}
这是我的服务界面:
public interface RetrofitRest {
@POST("/SF_UserLogin.svc/rest/login/{EMPLOYEECODE}/{PASSWORD}")
Call<ModelLogin>login(@Path("EMPLOYEECODE")String empcode,@Path("PASSWORD")String passwrd);
@GET("/SF_UserLogin.svc/rest/Msg")
Call<ModelLogin>verify(@Body ModelLogin result,@Body ModelLogin user_id);
}
我的主要活动如下:
package com.example.first.servicefirst;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import java.io.IOException;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
public class MainActivity extends Activity {
EditText password,userName;
Button login,resister;
ProgressBar progressbar;
TextView tv;
String TAG="Fails";
String url="http://172.16.7.203/sfAppServices/";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
password=(EditText) findViewById(R.id.password);
userName=(EditText) findViewById(R.id.txtEmployeeCode);
login=(Button) findViewById(R.id.btnsignin);
userName.setBackgroundResource(R.drawable.colorfoucs);
//progess_msz.setVisibility(View.GONE);
ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf=cn.getActiveNetworkInfo();
if(nf != null && nf.isConnected()==true )
{
Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();
} else {
showAlertDialog(MainActivity.this,"No Network","Please Check Your Network Connectivity",true);
}
final ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressbar = (ProgressBar) findViewById(R.id.progressBar);
progressbar.setVisibility(View.VISIBLE);
String s1 = userName.getText().toString();
String s2 = password.getText().toString();
if (s1.equals("")) {
userName.setError("Enter User Name");
}
if (s2.equals("")) {
password.setError("Enter Password");
}
try{
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
// Customize the request
Request request = original.newBuilder()
.header("Accept", "application/json")
.header("Authorization", "auth-token")
.method(original.method(), original.body())
.build();
com.squareup.okhttp.Response response = chain.proceed(request);
// Customize or return the response
return response;
}
});
Retrofit retro =
newRetrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
RetrofitRest retrofitRest = retro.create(RetrofitRest.class);
Call<ModelLogin>call=retrofitRest.login(s1, s2);
String result="";
String userid="";
Call<ModelLogin> callget=retrofitRest.verify();
callget.enqueue(new Callback<ModelLogin>() {
@Override
public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
if(result.equals(1))
{
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
else{
Toast.makeText(MainActivity.this, "Enter Valid Credentials",
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Throwable t) {
}
});
// call.enqueue(new Callback<ModelLogin>() {
// @Override
// public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
// }
// @Override
// public void onFailure(Throwable t) {
// Log.d(TAG,"Error");
// }
//});
}catch (Exception e){
throw e;
}
}
});
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
}
下面的代码是我的pojo:
package com.example.first.servicefirst;
import com.google.gson.annotations.SerializedName;
public class ModelLogin
{
@SerializedName("Result")
private String result;
public void setResult(String result) {
this.result = result;
}
public String getResult() {
return result;
}
@SerializedName("UserID")
private String userid;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
我的疑问是如何从Json字符串中单独检索结果和用户ID。不知道我在哪里做错了。
答案 0 :(得分:0)
如何使用改装:
POJOs
(确切名称为JSON
结果KEY
或使用SerializedName
按名称命名变量)INTERFACEs
参数GET
(POST
或CALLBACK
,具体取决于您愿意实现的行动)
CALLBACK
和success()
覆盖方法声明failure()
并成功处理响应,如果成功,则在您处理通话失败时失败答案 1 :(得分:0)
而不是
@GET("/SF_UserLogin.svc/rest/Msg")
Call<ModelLogin>verify(@Body ModelLogin result,@Body ModelLogin user_id);
}
使用
@GET("/SF_UserLogin.svc/rest/Msg")
Call<ModelLogin>verify(@Query("key_from_REST_API") int result,@Query("key_from_REST_API") int user_id);
答案 2 :(得分:0)
接口中的方法应该如下所示
@POST("/SF_UserLogin.svc/rest/login/{EMPLOYEECODE}/{PASSWORD}")
public void login(@Path("EMPLOYEECODE")String empcode, @Path("PASSWORD") String password, Callback<ModelLogin> callback);
并执行它:
retrofitRest.login(employee, pass, new Callback<ModelLogin>() {
@Override
public void success(ModelLogin model, Response response) {
// success!
}
@Override
public void failure(RetrofitError error) {
// fail
}
});
顺便说一句 您的pojo中的ModuleName和ModuleID在哪里?