改进POST请求身份验证令牌不接受

时间:2015-08-31 22:17:23

标签: android curl http-post retrofit

我正在尝试向我创建的REST API发送POST请求。为此,我正在使用Retrofit。

现在,当我在终端中使用CURL命令发送请求时,请求被接受并存储值。以下是代码:

curl -i -H "Accept: application/json" -H "Content-type: application/json" -H "X-User-Email: abcd@gmail.com" -H "X-User-Token: qQsQobQv-Wmum7bUs4b_"  -X POST -d '{"store": {"code":"0010" } }' http://localhost:3000/api/store.json

以上工作完全正常。

现在,当我尝试在我的Android应用程序中使用Retrofit发送请求时,它会在我的API中显示Unauthorization Error。没有任何东西可以存储。

final String endpoint = "http://localhost:3000/api/store.json"
RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader("Content-Type", "application/json");
                request.addHeader("Accept", "application/json");
                request.addHeader("X-User-Email", email);
                request.addHeader("X-User-Token", auth_token);
            }
        };

        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(endpoint)
                .setRequestInterceptor(requestInterceptor)
                .build();

        Service service = restAdapter.create(Service.class);
        service.store(fault, new Callback<StoreResponse>() {
            @Override
            public void success(StoreResponse storeResponse, Response response) {
                Log.d(LOG_TAG, "Success");
            }

            @Override
            public void failure(RetrofitError error) {
                Log.d(LOG_TAG, "Failure" + error.getMessage());
            }
        });

这不起作用。我不知道该怎么办。被困在这里一段时间了。 请帮忙!!!

这是服务类:

public interface Service {
    @POST("/")
    public void store(@Body StoreResponse fault, Callback<StoreResponse> responseCallback);
}

修改

现在工作正常。实际上我的电子邮件没有被存储,所以变量是null。修正了现在一切正常。

1 个答案:

答案 0 :(得分:0)

更改您的&#34;测试&#34;课程如下:

final String endpoint = "http://localhost:3000/api"

RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(endpoint)
                .build();

Service service = restAdapter.create(Service.class);
service.store(fault, new Callback<StoreResponse>() {
    @Override
    public void success(StoreResponse storeResponse, Response response) {
        Log.d(LOG_TAG, "Success");
    }

    @Override
    public void failure(RetrofitError error) {
        Log.d(LOG_TAG, "Failure" + error.getMessage());
    }
});

您的服务界面:

public interface Service {
   @Headers({"X-User-Email: abcd@gmail.com", "X-User-Token: qQsQobQv-Wmum7bUs4b_"})
   @POST("/store.json")
   public void store(@Body StoreResponse fault, Callback<StoreResponse> responseCallback);
}

或者如果您需要包含动态值的标题:

public interface Service {
   @POST("/store.json")
   public void store(@Header("X-User-Email") String email, @Header("X-User-Token") String token, @Body StoreResponse fault, Callback<StoreResponse> responseCallback);
}