使用Cookie Android获取JSON

时间:2016-11-21 13:50:22

标签: java android cookies android-volley retrofit2

如果我在我的网站上登录,我会得到一个cookie。该cookie有效期为一年,我希望它在我的Android应用程序中实现。使用该cookie我可以获得JSON数据,它可以在Postman中使用Interceptor扩展。 但在Android中,我无法让它发挥作用。我尝试过许多不同的方式:
Retrofit2:

public void GetCaregiver(){
    CookieInterceptor interceptor = new CookieInterceptor();
    interceptor.setSessionCookie("eyJpdiI6IjVcL1d6MEhLaGNZV3V2MFdVdFRtRVN3PT0iLCJ2YWx1ZSI6IldZWU42cUZQblcwejlDMk5LVllYOENXSThmVk9UUFIzaStxclZoUTFIRGlMazFlUzdjVDhFcTVxRllwMERncFFLZTVNQlQ0VUQ2SG5BSUE3TzJcL0Vrdz09IiwibWFjIjoiNDk3YmY3ZmE0NzA2Nzk1NzMwNTM0NDViOGNjNDllN2ZmZmYyNmNhNTdjNWYwOWYwYTIzZmI2YmI5OTc3OWZjNiJ9");
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .build();

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(zorggemakURL)
            .callFactory(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    RESTInterface service = retrofit.create(RESTInterface.class);

    Call<List<Caregiver>> call = service.getCaregivers();

    call.enqueue(new Callback<List<Caregiver>>() {
        @Override
        public void onResponse(Call<List<Caregiver>> call, retrofit2.Response<List<Caregiver>> response) {
            Log.d("Response", response.toString());
        }

        @Override
        public void onFailure(Call<List<Caregiver>> call, Throwable t) {
            Log.d("Response", t.toString());
        }
    });
}

排球:

 public void GetCaregiver() {
    // the request
    String url = zorggemakURL + "api/user/overview";

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
            url,
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    // response
                    Log.d("Response", response.toString());
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    Log.d("ERROR", "error => " + error.toString());
                }
            }) {

        @Override
        public String getBodyContentType() {
            return "application/x-www-form-urlencoded";
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Accept", "application/json");

            String creds = String.format("%s:%s", "orlandosmits", "test123");
            String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
            headers.put("Cookie", cookie);
            headers.put("Authorization", auth);

            return headers;
        }
    };
    Volley.newRequestQueue(context).add(request);
}

我将始终返回HTML页面而不是JSON数据。有人有想法吗?

1 个答案:

答案 0 :(得分:0)

我得到了它的工作。 最终代码:

public void GetCaregiver() {
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(new HeaderInterceptor()).build();

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(zorggemakURL)
            .callFactory(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    RESTInterface service = retrofit.create(RESTInterface.class);

    Call<List<Caregiver>> call = service.getCaregivers();

    call.enqueue(new Callback<List<Caregiver>>() {
        @Override
        public void onResponse(Call<List<Caregiver>> call, retrofit2.Response<List<Caregiver>> response) {
           List<Caregiver> caregivers = response.body();
            String test = "";
        }

        @Override
        public void onFailure(Call<List<Caregiver>> call, Throwable t) {
            Log.d("Response", t.toString());
        }
    });
}

HeaderInterceptor类:

public class HeaderInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain)
        throws IOException {
    Request request = chain.request();
    request = request.newBuilder()
            .addHeader("Cookie", "laravel_session=eyJpdiI6Im54UEpmbW9qdlc0a01FdG1uSGdNU3c9PSIsInZhbHVlIjoieGNuck96K0V2UWU1aG1vVE9DRDRQeWNQbEJ0UldEdWt2TUxFWjByVGVxckZ1a1NhcnE5dXMxTDBqTGtrcExQVEwzWkNQcTNSeHpUVXpFU3A5NHYxdEE9PSIsIm1hYyI6IjhlMzY0ODllYzEwOTFkNTYzZDU2ZmY1NTM5YTUyNmE0MTVlY2JmMjJkZDk0YmFiZmVhNDJmZDNkZmMwMTg5YWIifQ%3D%3D")
            .build();
    Response response = chain.proceed(request);
    return response;
}