头文件没有在android-Retrofit中正确设置

时间:2015-08-04 23:38:05

标签: java android http-headers retrofit

我正在构建一个应用程序,用于在Android中使用Retrofit向服务器发送访问令牌。我没有得到任何错误,我认为应该正确设置标题是不行的。

我想要的标题:

"Authorization: Bearer facebook <user_access_token>"

是我得到的令牌。出于安全考虑,此处不写。

我正在使用android Retrofit来处理文件,如下所示:

MainActivity.java

package com.example.apurva.myapplication;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.os.StrictMode;




public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        UserService userService;
        String token = "Bearer facebook <user_access_token>";
        userService = ServiceGenerator.createService(UserService.class, UserService.BASE_URL, token);
        User user = userService.me();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

UserService.java

package com.example.apurva.myapplication;

import com.squareup.okhttp.OkHttpClient;

import retrofit.Callback;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.http.POST;

/**
 * Created by apurva on 4/8/15.
 */
public interface UserService {

        public static final String BASE_URL = "http://10.0.2.2:8000/auth";

        @POST("/convert-token")
        User me();

}

ServiceGenerator.java

package com.example.apurva.myapplication;

import com.squareup.okhttp.OkHttpClient;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;

/**
 * Created by apurva on 4/8/15.
 */
public class ServiceGenerator {
    private ServiceGenerator() {
    }

    public static <S> S createService(Class<S> serviceClass, String baseUrl, final String token) {
        RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint(baseUrl)
                .setClient(new OkClient(new OkHttpClient()));

        if (token != null) {
            builder.setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    request.addHeader("Accept", "application/json");
                    request.addHeader("Authorization", token);
                }
            });
        }

        RestAdapter adapter = builder.build();
        return adapter.create(serviceClass);
    }
}

我想提一下,没有错误。我已经使用 StrictMode 在主线程中设置了网络活动,因此这不是问题,因为它没有提供所需的结果,因为用户未在后端添加。

我还想告诉你,我已经用cURL检查了我的后端,它运行正常,所以也没有问题。

我收到运行时错误:

&#13;
&#13;
Process: com.example.apurva.myapplication, PID: 7140
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.apurva.myapplication/com.example.apurva.myapplication.MainActivity}: retrofit.RetrofitError: 405 METHOD NOT ALLOWED
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: retrofit.RetrofitError: 405 METHOD NOT ALLOWED
            at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:388)
            at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
            at $Proxy0.me(Native Method)
            at com.example.apurva.myapplication.MainActivity.onCreate(MainActivity.java:24)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您的代码没问题。您应该将日志添加到您的Retrofit。

// Simple add .setLogLevel(RestAdapter.LogLevel.FULL)
RestAdapter.Builder builder = new RestAdapter.Builder()
                    .setLogLevel(RestAdapter.LogLevel.FULL)
                    .setEndpoint(baseUrl)
                    .setClient(new OkClient(new OkHttpClient()));

我确定在此之后你会在控制台中看到:

---> HTTP POST http://10.0.2.2:8000/auth/convert-token
Accept: application/json
Authorization: Bearer facebook <user_access_token>
---> END HTTP (no body)

这意味着你的标题设置正确。

&#34; HTTP 405方法不允许&#34;可能会说这个资源不期望POST方法。也许GET请求会帮助你:

 @GET("/convert-token")
 User me();

答案 1 :(得分:0)

嗨请参考githublink,它会给出一些想法,让我在这里解释一下基本功能, 创建一个接口:

public interface MyApiEndPointInterface {

   /* @GET("contacts/")
    Call<UserPojo> getHiveDetails();*/

    @FormUrlEncoded
    @POST("authorize/")
    Call<SmsLogin> getUser(@Field("username") String username,
                       @Field("password") String password);

    //GetProfile Details
     @GET("getprofile")
    Call<SmsProfilePojo> getProfileDetails(@Header("Authorizations") String myTokenValue);

}

UserProfilePreview.java是一个活动,请在repo中查找此类,它给出了基本的想法。

private void getApiCAll() {

        OkHttpClient okClient = new OkHttpClient.Builder() .addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                Request request = chain.request().newBuilder()
                        .addHeader("Accept","Application/JSON").build();
                return chain.proceed(request);
            }
        }).build();

         retrofitRef = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();


        final MyApiEndPointInterface service = retrofitRef.create(MyApiEndPointInterface.class);
        String myTokenStr = "Bearer "+mToken;
        Call<SmsProfilePojo> call = service.getProfileDetails(myTokenStr);
        call.enqueue(new Callback<SmsProfilePojo>() {
            @Override
            public void onResponse(Call<SmsProfilePojo> call, retrofit2.Response<SmsProfilePojo> response) {
                Log.d(TAG,"OnResponse: "+ response.code());

                if(response.isSuccessful()){

                    SmsProfilePojo result = response.body();
                    mToken = result.getToken();
                    txtVw_Token.setText(mToken);

                }else{
                    Toast.makeText(getApplicationContext(),"Fail in  Response",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<SmsProfilePojo> call, Throwable t) {
                Toast.makeText(getApplicationContext(),"Failed",Toast.LENGTH_SHORT).show();

            }
        });


    }