无法使用Retrofit2获取POST响应

时间:2017-11-02 17:12:15

标签: java android json android-studio retrofit2

我是一个新的Android开发人员,我正在尝试从我的服务器获得响应,但它只是在我尝试时才击中onFailure。我浏览了一个教程并尝试改变我的代码以实现我想要的方式。我的代码应该向我在服务器上创建的api发送用户名和密码,然后回复一个响应。这是我的代码:

LoginPage.java(MainActivity):

package com.example.azo.loginapp;

//Android packages
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

//Project packages
import com.example.azo.loginapp.data.model.Post;
import com.example.azo.loginapp.data.remote.APIService;
import com.example.azo.loginapp.data.remote.ApiUtils;

//Retrofit packages
import org.json.JSONException;
import org.json.JSONObject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginPage extends AppCompatActivity{
    private EditText Name;
    private EditText Password;
    private TextView Info;
    private Button Login;
    private int counter = 5;

    private APIService mAPIService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_page);
        mAPIService = ApiUtils.getAPIService();
        Name = findViewById(R.id.etName);
        Password = findViewById(R.id.etPass);
        Info = findViewById(R.id.tvInfo);
        Login = findViewById(R.id.btnLogin);

        Info.setText("No of attempts remaining: 5");

        Login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                validate(Name.getText().toString(),Password.getText().toString());
            }
        });
    }

    public void sendPost(String username, String password) {
        try {
            JSONObject paramObject = new JSONObject();
            paramObject.put("username", username);
            paramObject.put("password", password);
            Call<Post> postCall = mAPIService.savePost(paramObject.toString());
            postCall.enqueue(new Callback<Post>(){
                @Override
                public void onResponse(Call<Post> call,Response<Post> response) {
                    Toast.makeText(LoginPage.this, "It worked!",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(Call<Post> call, Throwable t) {
                    Toast.makeText(LoginPage.this, "Something went wrong :(", Toast.LENGTH_SHORT).show();
                }
            });
        }catch(JSONException e){
            e.printStackTrace();
        }
    }

    private void validate(String userName, String userPass){
        if(!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(userPass)){
            sendPost(userName, userPass);
        }else{
            counter--;
            Info.setText("No of atttempts remaining: " + String.valueOf(counter));
            if(counter == 0) {
                Login.setEnabled(false);
            }
        }
    }
}

APIService.java:

package com.example.azo.loginapp.data.remote;
import com.example.azo.loginapp.data.model.Post;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;
/**
  * Created by azotherian on 11/1/17.
 */

public interface APIService {
    @Headers("Content-Type: application/json")
    @POST("login")
    Call<Post> savePost(@Body String body);
}

Post.java:

package com.example.azo.loginapp.data.model;
/**
 * Created by azotherian on 11/1/17.
*/
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Post {
    @SerializedName("username")
    @Expose
    private String username;

    @SerializedName("password")
    @Expose
    private String password;

    public String getUsername(){
        return username;
    }

    public void setUsername(String username){
        username = username;
    }

    public String getPassword(){
        return password;
    }

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

    @Override
    public String toString(){
        return "Post{" +
            "username='" + username + '\'' +
            ", password='" + password + '\'' +
            '}';
    }
}

RetrofitClient.java:

package com.example.azo.loginapp.data.remote;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by azotherian on 11/1/17.
 */

public class RetrofitClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        }
        return retrofit;
    }
}

ApiUtils.java:

package com.example.azo.loginapp.data.remote;

/**
 * Created by azotherian on 11/1/17.
 */

public class ApiUtils {
    private ApiUtils() {}

    public static final String BASE_URL = "http://107.170.239.46/";

    public static APIService getAPIService() {
        return RetrofitClient.getClient(BASE_URL).create(APIService.class);
    }
}

如果需要更多信息,请告诉我们!谢谢你的时间!

1 个答案:

答案 0 :(得分:0)

经过一些研究和调试(感谢@AnkurKhandelwal和@JuanCruzSoler),我发现我的代码期待身体中的响应让gson解码。由于我没有从我的服务器传回任何身体,我不得不改变我的呼叫以使用虚空。此代码位于LoginPage.java

Call<Void> voidCall = mAPIService.savePost(paramObject.toString());
voidCall.enqueue(new Callback<Void>(){
    @Override
    public void onResponse(Call<Void> call, Response<Void> response) {
        Toast.makeText(LoginPage.this, "It worked!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(Call<Void> call, Throwable t) {
        Toast.makeText(LoginPage.this, "Something went wrong :(", Toast.LENGTH_SHORT).show();
        }
    });

我在<T>内更改了所有Post to Void。谢谢您的帮助!