【问题标题】:How to send cookies with AsyncTask?如何使用 AsyncTask 发送 cookie?
【发布时间】:2015-07-16 18:13:51
【问题描述】:

我有一个 Web 服务器,我在其中登录我的 android 应用程序,在登录之后,我将使用名为 token 的字段登录的用户作为 XML 接收。

此令牌用于在下次调用 webService 期间保持会话打开,它可以将令牌作为名为“acrsession”的 cookie 发送,但它似乎不起作用,因为每次我尝试检查我是否登录(使用 get调用名为 currentUser)它返回我被禁止,所以我认为它工作得不好。

这是我的 AsyncTask 类,负责调用服务器。

public String getFileName() {
        return FileName;
    }
    public void setFileName(String fileName) {
        FileName = fileName;
    }
    private String Response;
    private URI uriInfo;
    private String FileName;

    public WebServiceTask(int taskType, Context mContext, String processMessage,String token) {

        this.taskType = taskType;
        this.mContext = mContext;
        this.processMessage = processMessage;
        this.token=token;
    }


    public void addNameValuePair(String name, String value) {
        params.add(new BasicNameValuePair(name, value));
    }

    public void showProgressDialog() {  
        pDlg = new ProgressDialog(mContext);
        pDlg.setMessage(processMessage);
        pDlg.setProgressDrawable(mContext.getWallpaper());
        pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDlg.setCancelable(false);
        pDlg.show();
    }


    @Override
    protected void onPreExecute() {
        //hideKeyboard();
        showProgressDialog();
    }


    protected String doInBackground(String... urls) {
        String url = urls[0];
        String result = "";
        HttpResponse response = doResponse(url);
        if (response == null) {
            return result;
        } else {
            try {
                result = inputStreamToString(response.getEntity().getContent());

            } catch (IllegalStateException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);

            } catch (IOException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }

        }

        return result;
    }

    @Override
    protected void onPostExecute(String response) {     
        this.Response=response;
        pDlg.dismiss();
    }

    // Establish connection and socket (data retrieval) timeouts
    private HttpParams getHttpParams() {   
        HttpParams htpp = new BasicHttpParams();   
        HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
        HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);   
        return htpp;
    }

    private HttpResponse doResponse(String url) {         
        // Use our connection and data timeouts as parameters for our
        // DefaultHttpClient
        HttpClient httpclient = new DefaultHttpClient(getHttpParams());
        int responseCode=0;
        // Create a local instance of cookie store
        //CookieStore cookieStore = new BasicCookieStore();     
        // Create local HTTP context
        //HttpContext localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        //localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); 
        //CookieManager cookieManager= CookieManager.getInstance();
        this.getLocalContext();


        this.cookieStore.addCookie(new BasicClientCookie("acrsession", this.token));

        HttpResponse response = null; 
        try {
            switch (taskType) {

            case POST_TASK:
                HttpPost httppost = new HttpPost(url);
                // Add parameters
                httppost.setEntity(new UrlEncodedFormEntity(params));
                int executeCount = 0;
                do
                {
                    pDlg.setMessage("Logging in.. ("+(executeCount+1)+"/5)");
                    // Execute HTTP Post Request
                    executeCount++;
                    response = httpclient.execute(httppost,localContext);
                    responseCode = response.getStatusLine().getStatusCode();            
                    // If you want to see the response code, you can Log it
                    // out here by calling:
                    // Log.d("256 Design", "statusCode: " + responseCode)
                } while (executeCount < 5 && responseCode == 408);          
                uriInfo = httppost.getURI();               
                break;
            case GET_TASK:
                HttpGet httpget = new HttpGet(url);
                response = httpclient.execute(httpget,localContext);
                responseCode = response.getStatusLine().getStatusCode();
                httpget.getRequestLine();
                uriInfo = httpget.getURI();                    
                break;
            case PUT_TASK:
                HttpPut httpput = new HttpPut(url);
                File file = new File(this.FileName);
                InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
                reqEntity.setContentType("binary/octet-stream");
                reqEntity.setChunked(true); // Send in multiple parts if needed
                httpput.setEntity(reqEntity);
               response = httpclient.execute(httpput,localContext);
                responseCode = response.getStatusLine().getStatusCode();
                httpput.getRequestLine();
                uriInfo = httpput.getURI();                    
                break;
            }
        } catch (Exception e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }
        return response;
    }

    private String inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        try {
            // Read response until the end
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }
        // Return full string
        this.Response=total.toString();
        return total.toString();
    }
    public String getResponse(){
        return this.Response;
    }
    public HttpContext getLocalContext()
    {

        if (localContext == null)
        {
            localContext = new BasicHttpContext();
            cookieStore = new BasicCookieStore();
            localContext.setAttribute(ClientContext.COOKIE_ORIGIN, cookieStore);
            localContext.setAttribute(ClientContext.COOKIE_SPEC, cookieStore);
            localContext.setAttribute(ClientContext.COOKIESPEC_REGISTRY, cookieStore);
            localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);// to make sure that cookies provided by the server can be reused
        }
        return localContext;
    }

请告诉我我做错了什么。

提前致谢。

【问题讨论】:

    标签: java android cookies android-asynctask


    【解决方案1】:

    好吧,我终于找到了解决方案,一切正常,但我忘了设置 cookie 域和路径,所以一旦我把它放在了它的工作上。

    现在 cookie 创建如下所示:

    this.localContext=this.getLocalContext();
    BasicClientCookie cookie = new BasicClientCookie("acrsession", this.token);
    cookie.setDomain(this.Domain);
    cookie.setPath(this.path);
    this.cookieStore.addCookie(cookie);
     localContext.setAttribute(ClientContext.COOKIE_STORE, this.cookieStore);
    

    希望对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-03-14
      • 2010-09-23
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      • 2012-05-07
      • 2016-11-22
      • 2021-11-03
      相关资源
      最近更新 更多