如何使用翻新从服务器检索json?从我的服务器
JSON响应将是这样的:如何使用翻新从服务器检索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字符串中单独检索结果和userid。不知道我在做什么错误。
如何使用RETROFIT:
- 创建
POJOs
(以完全相同的名字作为JSON
结果KEY
或使用SerializedName
命名变量,如你所愿) - 创建取决于什么行动
INTERFACEs
(GET
或POST
你愿意实现)用CALLBACK
参数 - 声明
CALLBACK
用success()
和failure()
覆盖方法和成功,你处理响应,如果有成功,失败你处理失败的通话
哪里在我的代码中犯了错误可以ü请检查出来 –
这是我的错误:发现多个@Body方法注释。 (参数#2) 方法RetrofitRest.verify –
尝试谷歌这:多个@Body方法注释找到。 (参数#2)方法RetrofitRest.verify –
而不是
@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);
- 你的方法接口应公开
- 方法应该包含回调
所以在接口的方法应该是这样的
@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
}
});
BTW 哪里是模块名,并在的moduleId的POJO?
Guy使用Retrofit 2.所以方法签名是正确的。 –
只是评级下来,甚至没有回应形式我的问题 –
不是我downvote,但我相信downvoters不喜欢你如何提出你的问题。首先,你只需要发布相关的代码,而不是一切。其次,Json响应很奇怪,例如json中的字符串Json字符串。 – Sufian