如何将 Cookie 会话 ID 放入 volley 请求中? [英] How to put Cookie session id into volley request?

查看:33
本文介绍了如何将 Cookie 会话 ID 放入 volley 请求中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有这个代码可以用 volley 发出 POST 请求:

So, i have this code to make a POST request with volley:

public class MainActivity extends AppCompatActivity {

 Button btnSearch;
 ProgressDialog loadingDialog;
 ListView lvResult;
 String session_id;
 RequestQueue queue;
 MyCookieManager myCookieManager;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  btnSearch = (Button) findViewById(R.id.btnSearch);
  lvResult = (ListView) findViewById(R.id.lvResult);
  loadingDialog = new ProgressDialog(MainActivity.this);
  loadingDialog.setMessage("Wait.
Loading...");
  loadingDialog.setCancelable(false);
  myCookieManager = new MyCookieManager();

  requestCookie(); //FIRST CALL TO GET SESSION ID

  btnSearch.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    showLoading();
    requestWithSomeHttpHeaders(); //CALL TO MAKE THE REQUEST WITH VALID SESSION ID
   }
  });

 }

 public void requestCookie() {
  queue = Volley.newRequestQueue(this);
  String url = "http://myurl.com/json/";

  StringRequest postRequest = new StringRequest(Request.Method.POST, url,
   new Response.Listener < String > () {
    @Override
    public void onResponse(String response) {
     //
     String x = myCookieManager.getCookieValue();
    }
   },
   new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
     Log.d("ERROR", "Error => " + error.toString());
     hideLoading();
    }
   }
  ) {
   @Override
   public byte[] getBody() throws AuthFailureError {
    String httpPostBody = "param1=XPTO&param2=XPTO";
    return httpPostBody.getBytes();
   }

   @Override
   public Map < String, String > getHeaders() throws AuthFailureError {
    Map <String, String> params = new HashMap < String, String > ();
    params.put("User-Agent", "Mozilla/5.0");
    params.put("Accept", "application/json, text/javascript, */*; q=0.01");
    params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    //params.put("Set-Cookie", session_id);// + " _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
    //"PHPSESSID=ra0nbm0l22gsnl6s4jo0qkqci1");
    return params;
   }

   protected Response <String> parseNetworkResponse(NetworkResponse response) {
    try {
     String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
     String header_response = String.valueOf(response.headers.values());
     int index1 = header_response.indexOf("PHPSESSID=");
     int index2 = header_response.indexOf("; path");
     //Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
     session_id = header_response.substring(index1, index2);

     return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
     return Response.error(new ParseError(e));
    }
   }
  };

  queue.add(postRequest);
 }

 public void requestWithSomeHttpHeaders() {
  queue = Volley.newRequestQueue(this);
  String url = "http://myurl.com/json/";

  StringRequest postRequest = new StringRequest(Request.Method.POST, url,
   new Response.Listener <String> () {
    @Override
    public void onResponse(String response) {
     Log.d("Response", response);
     String x = myCookieManager.getCookieValue();
     String status = "";

     try {
      JSONObject resultObject = new JSONObject(response);
      Log.d("JSON RESULT =>", resultObject.toString());
     } catch (JSONException e) {
      Toast.makeText(MainActivity.this, "Request Error", Toast.LENGTH_SHORT).show();
      e.printStackTrace();
     }

     hideLoading();
    }
   },
   new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
     Log.d("ERROR", "Error => " + error.toString());
     hideLoading();
    }
   }
  ) {
   @Override
   public byte[] getBody() throws AuthFailureError {
    String httpPostBody = "param1=XPTO&param2=XPTO";
    return httpPostBody.getBytes();
   }

   @Override
   public Map <String, String> getHeaders() throws AuthFailureError {
    Map <String, String> params = new HashMap <String, String> ();
    params.put("User-Agent", "Mozilla/5.0");
    params.put("Accept", "application/json, text/javascript, */*; q=0.01");
    params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    params.put("Cookie", /*myCookieManager.getCookieValue()*/ session_id + "; _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
    return params;
   }
  };

  queue.add(postRequest);
 }

 private void showLoading() {
  runOnUiThread(new Runnable() {
   @Override
   public void run() {
    if (!loadingDialog.isShowing())
     loadingDialog.show();
   }
  });
 }

 private void hideLoading() {
  runOnUiThread(new Runnable() {
   @Override
   public void run() {
    if (loadingDialog.isShowing())
     loadingDialog.dismiss();
   }
  });
 }
}

如果我发送一个有效的 cookie ID,这将返回一个有效的 JSON 对象,否则返回一个空对象.

If I send a valid cookie ID this return a valid JSON object else a empty object.

我尝试(未成功)设置默认 cookie 句柄,例如

I tried (unsuccessfully) to set default cookie handles like

CookieManager manager = new CookieManager();CookieHandler.setDefault(manager);

但我得到一个空对象.

如何将有效的 cookie 会话 ID 放入发布请求?

推荐答案

所以问题是获取有效的 cookie.我的错误是从 POST 请求本身获取它.我保持相同的工作原理,在启动应用程序时获取 cookie,但使用 GET 而不是 POST 并调用 URL 的根而不是获取 JSON 的地址.

So the problem was getting a valid cookie. My mistake was to get it from the POST request itself. I kept the same working principle, getting the cookie when I started the application but using GET instead of POST and calling the root of the URL instead of the address where I get the JSON.

我的解决方案如下:

public void requestCookie() {
  queue = Volley.newRequestQueue(this);
  String url = "http://myurl.com/";

  StringRequest getRequest = new StringRequest(Request.Method.GET, url,
   new Response.Listener <String> () {
    @Override
    public void onResponse(String response) {
     String x = myCookieManager.getCookieValue();
    }
   },
   new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
     Log.d("ERROR", "Error => " + error.toString());
     hideLoading();
    }
   }
  ) {   
   protected Response <String> parseNetworkResponse(NetworkResponse response) {
    try {
     String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
     String header_response = String.valueOf(response.headers.values());
     int index1 = header_response.indexOf("PHPSESSID=");
     int index2 = header_response.indexOf("; path");
     //Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
     session_id = header_response.substring(index1, index2);

     return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
     return Response.error(new ParseError(e));
    }
   }
  };

  queue.add(getRequest);
 }

这篇关于如何将 Cookie 会话 ID 放入 volley 请求中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆