需要帮助改造登录示例?

时间:2015-11-04 05:38:16

标签: android retrofit

http://172.16.7.203/sfAppServices/SF_UserLogin.svc/rest/login/

在这个用户名和密码是其中的一部分我需要发布用户从edittext输入的用户名和密码,并获得像这样的json响应

{"Result":"1","UserID":"0"} 

如何使用改造来获得json。我用asynctask成功地做到了这一点。但通过改造感觉很难实现。 我的问题是

  • 哪个是基本网址?
  • 在接口中应该以post方法公开。
  • 如何通过json从休息服务中获取json响应。

以下是我的主要活动:

 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 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 url="http://172.16.7.203/sfAppServices/SF_UserLogin.svc/rest/login/";

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);


          login();

        }
    });


}

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();
}
public void login(){
Retrofit retro = new   
Retrofit.Builder().baseUrl("http://172.16.7.203").addConverterFactory(GsonConverterFactory.create()).build();
RetrofitRest retrofitRest = retro.create(RetrofitRest.class);
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");
}

retrofitRest.login(s1,s2, new Callback<ModelLogin>() {
    @Override
    public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
        Intent intent = new Intent(MainActivity.this, Main2Activity.class);
        startActivity(intent);
    }

    @Override
    public void onFailure(Throwable t) {

    }
});
 }
 }

以下是我的界面:

 public interface RetrofitRest {
@FormUrlEncoded
@POST("/sfAppServices/SF_UserLogin.svc/rest/login/")
Callback<ModelLogin> login(@Query("empcode") String employeecode, @Query("password") String password,       
Callback<ModelLogin> callback);
 }

我的pojo:

 package com.example.first.servicefirst;

import com.google.gson.annotations.SerializedName;

public class ModelLogin {

private String empcode;
private ModelLogin(){}
@SerializedName("Result")
private String result;
public String getResult(){
    return result;
}
private String password;
public String getEmpcode() {
    return empcode;
}


public String getPassword() {
    return password;
}

public void setEmpcode(String empcode) {
    this.empcode = empcode;
}



public void setPassword(String password) {
    this.password = password;
}

}

2 个答案:

答案 0 :(得分:1)

由于您的请求参数是路径参数,因此您的请求不需要DTO。只需为此响应创建一个DTO即可。

public class LoginResponseDto {
    @SerializedName("Result")
    private String result;
    @SerializedName("UserID")
    private String userId;

    // Getters & Setters etc.
}

然后解析您的URL并创建您的服务界面。我认为您的基本网址将是“http://172.16.7.203/sfAppServices/”,其他用于服务识别。它高度依赖于您可能想要使用的其他服务。如果您只是使用登录服务,您甚至可以将此基本网址设为“http://172.16.7.203/sfAppServices/SF_UserLogin.svc”,但这些决定会更改您的服务注释。

public interface LoginService{
    @POST("/SF_UserLogin.svc/rest/login/{employeeCode}/{password}") // Assume your base url is http://172.16.7.203/sfAppServices/
    public void login(@Path("employeeCode") String employeeCode, @Path("password") String password, Callback<LoginResponseDto> callback);
} 

最后你的改造实例。您不应该一遍又一遍地创建Retrofit实例。而是在您的应用程序中创建它或使用单例模式,并在需要时获取LoginService

更新

由于您使用的是Retrofit 2,您应该使用这样的服务。

public interface LoginService{
    @POST("/SF_UserLogin.svc/rest/login/{employeeCode}/{password}") // Assume your base url is http://172.16.7.203/sfAppServices/
    public Call<LoginResponseDto> login(@Path("employeeCode") String employeeCode, @Path("password") String password);
} 

答案 1 :(得分:0)

在您的活动中写下以下代码

private void callLoginApi()
{

    ApiListeners apiListener;

    Retrofit retrofit = Retrofit.Builder().baseUrl("http://172.16.7.203/sfAppServices/SF_UserLogin.svc/rest/").build();

    apiListener = retrofit.create(ApiListeners.class);

    apiListener.loginUser("test@test.com", "123456",new Callback<String>() 
        {
            @Override
            public void success(String response, retrofit.client.Response arg1) 
            {
                CommonUtills.dismissProgressDialog();
                if(response != null && !response.isEmpty())
                {
                    // Do what you want after getting success
                }
            }

            @Override
            public void failure(RetrofitError error) 
            {
                // Do what you want after getting failure
            }
        });
}

回调你可以根据需要改变它

您需要创建一个界面,您需要在其中创建登录API调用方法

@FormUrlEncoded
@POST("/login")
public void loginUser(@Field("email") String email,@Field("password") String password,retrofit.Callback<String> response);
相关问题