2015-11-05 76 views
-1

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。不知道我在做什麼錯誤。

+0

只是評級下來,甚至沒有迴應形式我的問題 –

+0

不是我downvote,但我相信downvoters不喜歡你如何提出你的問題。首先,你只需要發佈相關的代碼,而不是一切。其次,Json響應很奇怪,例如json中的字符串Json字符串。 – Sufian

回答

0

如何使用RETROFIT:

  • 創建POJOs(以完全相同的名字作爲JSON結果KEY或使用SerializedName命名變量,如你所願)
  • 創建取決於什麼行動INTERFACEsGETPOST你願意實現)用CALLBACK參數
  • 聲明CALLBACKsuccess()failure()覆蓋方法和成功,你處理響應,如果有成功,失敗你處理失敗的通話
+0

哪裏在我的代碼中犯了錯誤可以ü請檢查出來 –

+0

這是我的錯誤:發現多個@Body方法註釋。 (參數#2) 方法RetrofitRest.verify –

+0

嘗試谷歌這:多個@Body方法註釋找到。 (參數#2)方法RetrofitRest.verify –

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); 
0
  1. 你的方法接口應公開
  2. 方法應該包含回調

所以在接口的方法應該是這樣的

@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?

+0

Guy使用Retrofit 2.所以方法簽名是正確的。 –